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.
#include <iostream>
#include <conio.h>
using namespace std;
int main(int argc, char **argv)
{
cout<<"Enter the dimensions of the matrix: ";
int m, n;
cin>>m>>n;
double mat[m][n];
int zeros = 0;
cout<<"Enter the elements of the matrix: ";
for(int i=0; i<m; i++)
{
for(int j=0; j<n; j++)
{
cin>>mat[i][j];
if(mat[i][j] == 0)
{
zeros++;
}
}
}
if(zeros > (m*n)/2)
{
cout<<"The matrix is a sparse matrix";
}
else
{
cout<<"The matrix is not a sparse matrix";
}
}
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]Related Posts:
- Check Programming Books
- Apply for Computer Science Internship
- Apply for C++ Internship
- Check C++ Books
- Check Computer Science Books