C Program to Check if a Matrix is a Sparse Matrix

This C program is used to check if a matrix is a sparse Matrix. If the number of zeros in a matrix exceeds (n*m)/2, where n, m is the dimension of the matrix, matrix is sparse matrix. Sparse matrix has more zero elements than nonzero elements.

Here is the source code of the C program to find out is a given matrix is a sparse matrix. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

/*

* C Program to check if a Matrix is a Sparse Matrix

*/

#include <stdio.h>

void main ()

{

int matrix[10][10];

int i, j, m, n;

int sparse_counter =0;

printf("Enter the order of the matix \n");

scanf("%d %d",&m,&n);

printf("Enter the elements of the matix \n");

for(i =0; i < m;++i)

{

for(j =0; j < n;++j)

{

scanf("%d",&matrix[i][j]);

if(matrix[i][j]==0)

{

++sparse_counter;

}

}

}

if(sparse_counter >((m * n)/2))

{

printf("The given matrix is Sparse Matrix !!! \n");

}

else

printf("The given matrix is not a Sparse Matrix \n");

printf("There are %d number of Zeros.", sparse_counter);

}

advertisements

$ gcc sparse_matrix.c -o sparse_matrix
$ ./sparse_matrix
Enter the order of the matix 33
Enter the elements of the matix
123400000
The given matrix is Sparse Matrix !!!
There are 5 number of Zeros.