
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check If a Matrix is Sparse in C++
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
#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;