C++ Program to Check if it 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:

advertisement
$ 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

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

advertisement
advertisement
advertisement
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