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

C++ProgrammingServer Side Programming

A sparse matrix is a matrix in which majority of the elements are 0. In other words, if more than half of the elements in the matrix are 0, it is known as a sparse matrix. For example −

The matrix given below contains 5 zeroes. Since the number of zeroes is more than half the elements of the matrix, it is a sparse matrix.

1 0 2
5 0 0
0 0 9

A program to check if it is a sparse matrix or not is as follows.

Example

Live Demo

#include<iostream>
using namespace std;
int main () {
int a[10][10] = { {2, 0, 0} , {0, 3, 8} , {0, 9, 0} };
int i, j, count = 0;
int r = 3, c = 3;
for (i = 0; i < r; ++i) {
for (j = 0; j < c; ++j) {
if (a[i][j] == 0)
count++;
}
}
cout<<"The matrix is:"<<endl;
for (i = 0; i < r; ++i) {
for (j = 0; j < c; ++j) {
cout<<a[i][j]<<" ";
}
cout<<endl;
}
cout<<"There are "<<count<<" zeros in the matrix"<<endl;
if (count > ((r * c)/ 2))
cout<<"This is a sparse matrix"<<endl;
else
cout<<"This is not a sparse matrix"<<endl;
return 0;
}

Output

The matrix is:
2 0 0
0 3 8
0 9 0
There are 5 zeros in the matrix
This is a sparse matrix

In the above program, a nested for loop is used to count the number of zeros in the matrix. This is demonstrated using the following code snippet.

for (i = 0; i < r; ++i) {
for (j = 0; j < c; ++j) {
if (a[i][j] == 0)
count++;
}
}

After finding the number of zeros, the matrix is displayed using a nested for loop. This is shown below −

cout<<"The matrix is:"<<endl;
for (i = 0; i < r; ++i) {
for (j = 0; j < c; ++j) {
cout<<a[i][j]<<" ";
}
cout<<endl;
}

Finally, the number of zeroes are displayed. If the count of zeros is more than half the elements in the matrix, then it is displayed that the matrix is a sparse matrix otherwise the matrix is not a sparse matrix.

cout<<"There are "<<count<<" zeros in the matrix"<<endl;
if (count > ((r * c)/ 2))
cout<<"This is a sparse matrix"<<endl;
else
cout<<"This is not a sparse matrix"<<endl;
Published on 05-Oct-2018 08:11:33