TheAlgorithms-C-Plus-Plus/Others/Sparse matrix.cpp

42 lines
861 B
C++
Raw Normal View History

2017-12-24 01:30:49 +08:00
/*A sparse matrix is a matrix which has number of zeroes greater than (m*n)/2,
where m and n are the dimensions of the matrix.*/
#include <iostream>
2018-03-27 23:51:33 +08:00
using namespace std;
2017-12-24 01:30:49 +08:00
int main()
{
2018-03-27 23:51:33 +08:00
int m,n;
int counterZeros=0;
cout << "Enter dimensions of matrix (seperated with space): ";
2017-12-24 01:30:49 +08:00
cin >> m >> n;
int a[m][n];
cout << "Enter matrix elements:";
2018-03-27 23:51:33 +08:00
cout << "\n";
// reads the matrix from stdin
for(int i=0;i<m;i++)
2017-12-24 01:30:49 +08:00
{
2018-03-27 23:51:33 +08:00
for(int j=0;j<n;j++)
{
cout << "element? ";
cin >> a[i][j];
}
2017-12-24 01:30:49 +08:00
}
2018-03-27 23:51:33 +08:00
// counts the zero's
for(int i=0;i<m;i++)
2017-12-24 01:30:49 +08:00
{
2018-03-27 23:51:33 +08:00
for(int j=0;j<n;j++)
2017-12-24 01:30:49 +08:00
{
if(a[i][j]==0)
2018-03-27 23:51:33 +08:00
counterZeros++; //Counting number of zeroes
2017-12-24 01:30:49 +08:00
}
}
2018-03-27 23:51:33 +08:00
// makes sure the matrix is a sparse matrix
if(counterZeros>((m*n)/2)) //Checking for sparse matrix
2017-12-24 01:30:49 +08:00
cout << "Sparse matrix";
else
cout << "Not a sparse matrix";
}