C Program for establishing whether the Matrix is Sparse

CWC
2 Min Read

C Program for establishing whether the Matrix is Sparse

A matrix is considered sparse when it has more zero values than non-zero values and dense when it has more non-zero values. In this program, we will see how to find out whether the specified matrix is sparse.

We need to specify the order of the matrix. Then, you will be prompted to enter the elements in the matrix. Once the elements of the matrix are entered, count the number of zeros in it. A counter for this purpose is initialized to 0. Using nested loops, each of the matrix
elements are scanned and, upon finding any zero elements, the value of the counter is incremented by 1.

#include 
#define max 100
/*A sparse matrix has more zero elements than nonzero elements */
void main ()
{
 static int arr[max][max];
 int i,j,r,c;
 int ctr=0;
 printf("How many rows and columns are in this matrix? ");
 scanf("%d %d", &r, &c);
 printf("Enter the elements in the matrix :\n");
 for(i=0;i<r;i++)
 {
 for(j=0;j<c;j++) { scanf("%d",&arr[i][j]); if (arr[i][j]==0) ++ctr; } } if (ctr>((r*c)/2))
 printf ("The given matrix is a sparse matrix. \n");
 else
 printf ("The given matrix is not a sparse matrix.\n");
 printf ("There are %d number of zeros in the matrix.\n",ctr);
}
Share This Article
Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *

English
Exit mobile version