
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++
What is Sparse Matrix?
A sparse matrix is a matrix in which the majority of the elements are zero. In other words, if more than half of the elements in a matrix are 0, it is called a sparse matrix. In this article, we will show you how to write a C++ program to check whether a given matrix is sparse or not.
Let's understand this with an example. The matrix shown below contains 5 zeros. Since the number of zeros is more than half of the total elements (9), it is a sparse matrix:
1 0 2 5 0 0 0 0 9
Steps to Check if a Matrix is Sparse
We can check if a matrix is sparse by counting how many elements are zero and comparing that count to the total number of elements. Here's how we did it:
- First, we define the matrix a and initialize it with values.
- Next, we use loops to count how many elements in the matrix are zero.
- Then, we compare the count of zeros with half of the total number of elements. If the number of zeros is greater than half, the matrix is sparse otherwise it is not.
- Finally, we print the matrix, the zero count, and the result.
C++ Program to Check if a Matrix is Sparse
In this example, we write a complete C++ program that helps us check whether a matrix is sparse or not.
#include<iostream> using namespace std; int main () { // Initialize the matrix with some values int a[10][10] = { {2, 0, 0} , {0, 3, 8} , {0, 9, 0} }; int i, j, count = 0; int r = 3, c = 3; // Count the number of zeros in the matrix for (i = 0; i < r; ++i) { for (j = 0; j < c; ++j) { if (a[i][j] == 0) count++; } } // Print the matrix cout<<"The matrix is:"<<endl; for (i = 0; i < r; ++i) { for (j = 0; j < c; ++j) { cout<<a[i][j]<<" "; } cout<<endl; } // Show how many zeros are in the matrix cout<<"There are "<<count<<" zeros in the matrix"<<endl; // Check if the matrix is sparse or not if (count > ((r * c) / 2)) cout<<"This is a sparse matrix"<<endl; else cout<<"This is not a sparse matrix"<<endl; return 0; }
Below you will see the output of the above program which checks and confirms whether the given matrix is sparse or not.
The matrix is: 2 0 0 0 3 8 0 9 0 There are 5 zeros in the matrix This is a sparse matrix
Time Complexity: O(r1*c1) because we use two nested loops.
Space Complexity: O(1) because we use constant amount of space.