C Program to Check Whether a Matrix Is Sparse or Not

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 post, let's write a C program to find out whether the specified matrix is sparse.

C Program to Check Whether a Matrix Is Sparse or Not

Let's create a file named sparsematrix.c and add the following source code to it.
#include <stdio.h>
#define max 100
/*A sparse martix is matrix which  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 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\n",ctr);
}

To compile and run the above C program, you can use C Programs Compiler Online tool.

Output:

How many rows and columns are in this matrix? 4 4
Enter the elements in the matrix :
0 1 0 0
5 0 0 9
0 0 3 0
2 0 4 0
The given matrix is a sparse matrix.
There are 10 zeros in the matrix.

Okay. Let's run the program again to see the output when the count of non-zero values is higher:

How many rows and columns are in this matrix? 4 4
Enter the elements in the matrix:
1 0 3 4
0 0 2 9
8 6 5 1
0 7 0 4
The given matrix is not a sparse matrix.
There are 5 zeros in the matrix.

We've successfully identified a sparse and a non-sparse matrix.


Comments