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

42 lines
901 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()
{
2019-08-21 10:10:08 +08:00
int m, n;
int counterZeros = 0;
2018-03-27 23:51:33 +08:00
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
2019-08-21 10:10:08 +08:00
for (int i = 0; i < m; i++)
2017-12-24 01:30:49 +08:00
{
2019-08-21 10:10:08 +08:00
for (int j = 0; j < n; j++)
2018-03-27 23:51:33 +08:00
{
2019-08-21 10:10:08 +08:00
cout << "element? ";
cin >> a[i][j];
2018-03-27 23:51:33 +08:00
}
2017-12-24 01:30:49 +08:00
}
2018-03-27 23:51:33 +08:00
// counts the zero's
2019-08-21 10:10:08 +08:00
for (int i = 0; i < m; i++)
2017-12-24 01:30:49 +08:00
{
2019-08-21 10:10:08 +08:00
for (int j = 0; j < n; j++)
2017-12-24 01:30:49 +08:00
{
2019-08-21 10:10:08 +08:00
if (a[i][j] == 0)
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
2019-08-21 10:10:08 +08:00
if (counterZeros > ((m * n) / 2)) //Checking for sparse matrix
cout << "Sparse matrix";
2017-12-24 01:30:49 +08:00
else
2019-08-21 10:10:08 +08:00
cout << "Not a sparse matrix";
2017-12-24 01:30:49 +08:00
}