C Program to check if a given matrix is sparse or not

February 3, 2022, Learn eTutorial

For a better understanding, we always recommend you to learn the basic topics of C programming listed below:

What is a sparse matrix?

In this program, we need to check whether the given matrix is the sparse matrix. A sparse matrix is a matrix that has more zero elements than non-zero elements; it is used to store the elements with a large number of zero elements. An example of a sparse matrix is shown below.

5 0 0
0 4 0
3 0 0

Here the matrix a has 6 zero elements and three non-zero elements so that we can call the matrix a sparse matrix.

In this example, so we need to check how many zeros and non-zeros elements are there in a matrix. So we accept a matrix, and we start a for loop to check each element of the matrix, then we use a counter and increment that counter every time we meet a zero element. Now we check the counter is greater than '[m*n]/2'; if it is correct, we print it as a sparse matrix. Else we print not a sparse matrix. It is a simple matrix c program.


STEP 1: Include the header files to use the built-in Functions in the C program.

STEP 2: Declare the variable i,j,m,n,counter,m1[10][10] as integer .

STEP 3: Read the order of the Matrix from the user into the variables m and n.

STEP 4: Read the coefficients of the Matrix by using for loop into the matrix m1[i[j].

STEP 5: Check m1[i][j]=0 ,if true then increment the counter by 1 and repeat step 4.

STEP 6: Check if counter>(m*n)/2, then display the given Matrix as a sparse matrix. Else do step 7.

STEP 7: Else display the given Matrix is not a sparse matrix.

STEP 8: Display There is a counter number of zeros by using the printf function.

C Source Code

                                          #include <stdio.h>

void main()
  static int m1[10][10];
  int i, j, m, n;
  int counter = 0;
  printf("Enter the order of the matix\n");
  scanf("%d %d", & m, & n);
  printf("Enter the coefficients of the matix\n");
  for (i = 0; i < m; ++i)
    for (j = 0; j < n; ++j)
      scanf("%d", & m1[i][j]);
      if (m1[i][j] == 0)
  if (counter > ((m * n) / 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", counter);
} /* EN dof main() */ /*end of main() */


Enter the order of the matrix

Enter the coefficients of the matrix
1 2
3 4

The given matrix is not a sparse matrix
There are 0 number of zeros

Run 2

Enter the order of the matrix

Enter the co-efficiency of the matrix
1 0 0
0 0 1
0 1 0
The given matrix is a sparse matrix

There are 6 number of zeros