C++ Program to Check if a Matrix is a Sparse Matrix

This is a C++ Program to check sparsity of a given 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.

Here is source code of the C++ Program to Check if it is a Sparse Matrix. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. #include <iostream>
  2. #include <conio.h>
  3.  
  4. using namespace std;
  5. int main(int argc, char **argv)
  6. {
  7.     cout<<"Enter the dimensions of the matrix: ";
  8.     int m, n;
  9.     cin>>m>>n;
  10.     double mat[m][n];
  11.     int zeros = 0;
  12.     cout<<"Enter the elements of the matrix: ";
  13.     for(int i=0; i<m; i++)
  14.     {
  15.         for(int j=0; j<n; j++)
  16.         {
  17.             cin>>mat[i][j];
  18.             if(mat[i][j] == 0)
  19.             {
  20.                 zeros++;
  21.             }
  22.         }
  23.     }
  24.  
  25.     if(zeros > (m*n)/2)
  26.     {
  27.         cout<<"The matrix is a sparse matrix";
  28.     }
  29.     else
  30.     {
  31.         cout<<"The matrix is not a sparse matrix";
  32.     }
  33.  
  34. }

Output:

$ g++ SparsityOfMatrix.cpp
$ a.out
 
Enter the dimensions of the matrix: 
3 3
 
Enter the elements of the matrix: 
1 2 3
4 5 6
0 0 0
 
The matrix is not a sparse matrix
 
 
Enter the dimensions of the matrix: 
3 3
 
Enter the elements of the matrix: 
1 1 0
0 0 1
1 0 0
 
The matrix is a sparse matrix

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

advertisement
advertisement

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

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). 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!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.