Home » Blog » C Program to check whether a two-dimensional array is a Sparse Matrix

# C Program to check whether a two-dimensional array is a Sparse Matrix In this program, you’ll learn how to check whether a two dimensional array is a Sparse Matrix.

Before we move forward with the program lets first understand what is Sparse Matrix.

A Sparse Matrix is a matrix(two-dimensional array) in which number of 0’s is greater than the number of non-zero elements.

or

A sparse matrix or sparse array is a matrix in which most of the elements are zero. By contrast, if most of the elements are nonzero, then the matrix is considered dense.

#### Program to check if the given 2D array is a Sparse Matrix or not

``````#include<stdio.h>

int main()
{
int a, b, c, d, matrix;
int counter = 0;
printf("\nEnter the number of rows and columns of the matrix \n\n");
scanf("%d%d",&b,&a);

printf("\nEnter the %d elements of the matrix \n\n", b*a);
for(c = 0; c < b; c++)   // to iterate the rows
{
for(d = 0; d < a; d++)   // to iterate the columns
{
scanf("%d", &matrix[c][d]);
if(matrix[c][d] == 0)
counter++;  // same as counter=counter +1
}
}

// to print a matrix
printf("\n\nThe entered matrix is: \n\n");
for(c = 0; c < b; c++)   // to iterate the rows
{
for(d = 0; d < a; d++)
{
printf("%d\t", matrix[c][d]);
}
printf("\n"); // to take the control to the next row
}

// checking if the matrix is sparse or not
if(counter > (b*a)/2)
printf("\n\nThis matrix is a sparse matrix\n\n");
else
printf("\n\nThis matrix is not a sparse matrix\n\n");

return 0;
}``````

Output

``````Enter the number of rows and columns of the matrix

2
3

Enter the 6 elements of the matrix

2
4
5
2
6
3

The entered matrix is:

2       4       5
2       6       3

This matrix is not a sparse matrix ``````