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.

  1. /*
  2.  * C Program to check if a Matrix is a Sparse Matrix
  3.  */
  4. #include <stdio.h>
  5.  
  6. void main ()
  7. {
  8.     int matrix[10][10];
  9.     int i, j, m, n;
  10.     int sparse_counter = 0;
  11.  
  12.     printf("Enter the order of the matix \n");
  13.     scanf("%d %d", &m, &n);
  14.     printf("Enter the elements of the matix \n");
  15.     for (i = 0; i < m; ++i)
  16.     {
  17.         for (j = 0; j < n; ++j)
  18.         {
  19.             scanf("%d", &matrix[i][j]);
  20.             if (matrix[i][j] == 0)
  21.             {
  22.                 ++sparse_counter;
  23.             }
  24.         }
  25.     }
  26.     if (sparse_counter > ((m * n) / 2))
  27.     {
  28.         printf("The given matrix is Sparse Matrix !!! \n");
  29.     }
  30.     else
  31.         printf("The given matrix is not a Sparse Matrix \n");
  32.     printf("There are %d number of Zeros.", sparse_counter);
  33. }

advertisement
$ gcc sparse_matrix.c -o sparse_matrix
$ ./sparse_matrix
 
Enter the order of the matix 3 3
Enter the elements of the matix 
1 2 3
4 0 0
0 0 0
The given matrix is Sparse Matrix  !!!
There are 5 number of Zeros.

Sanfoundry Global Education & Learning Series – 1000 C Programs.

advertisement
advertisement

Here’s the list of Best Reference Books in C Programming, Data Structures and Algorithms.

Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!
advertisement
advertisement
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer & SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage, Advanced C Programming, SAN Storage Technologies, SCSI Internals & Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him @ LinkedIn | Youtube | Instagram | Facebook | Twitter