Saturday, July 12, 2025
HomeData Modelling & AIC++ Program to Check if a given matrix is sparse or not

C++ Program to Check if a given matrix is sparse or not

A matrix is a two-dimensional data object having m rows and n columns, therefore a total of m*n values. If most of the values of a matrix are 0 then we say that the matrix is sparse. 
Consider a definition of Sparse where a matrix is considered sparse if the number of 0s is more than half of the elements in the matrix,

Examples: 

Input : 1 0 3
        0 0 4
        6 0 0
Output : Yes
There are 5 zeros. This count
is more than half of matrix
size.

Input : 1 2 3
        0 7 8
        5 0 7 
Output: No 

To check whether a matrix is a sparse matrix, we only need to check the total number of elements that are equal to zero. If this count is more than (m * n)/2, we return true. 

C++




// CPP code to check if a matrix is
// sparse.
#include <iostream>
using namespace std;
 
const int MAX = 100;
 
bool isSparse(int array[][MAX], int m, int n)
{
    int counter = 0;
 
    // Count number of zeros in the matrix
    for (int i = 0; i < m; ++i)
        for (int j = 0; j < n; ++j)
            if (array[i][j] == 0)
                ++counter;
 
    return (counter > ((m * n) / 2));
}
 
// Driver Function
int main()
{
    int array[][MAX] = { { 1, 0, 3 },
                        { 0, 0, 4 },
                        { 6, 0, 0 } };
 
    int m = 3,
        n = 3;
    if (isSparse(array, m, n))
        cout << "Yes";
    else
        cout << "No";
}


Output:  

Yes

Time complexity: O(m*n) where m and n are rows and columns respectively of a given matrix

Auxiliary Space: O(1)

Please refer complete article on Check if a given matrix is sparse or not for more details!

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32132 POSTS0 COMMENTS
Milvus
67 POSTS0 COMMENTS
Nango Kala
6516 POSTS0 COMMENTS
Nicole Veronica
11663 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11720 POSTS0 COMMENTS
Shaida Kate Naidoo
6608 POSTS0 COMMENTS
Ted Musemwa
6873 POSTS0 COMMENTS
Thapelo Manthata
6570 POSTS0 COMMENTS
Umr Jansen
6561 POSTS0 COMMENTS