C++ program to check whether the matrix is a sparse matrix or not using class

Submitted by Shubh Pachori, on September 17, 2022

Problem statement

Given a matrix, we to check whether it is a sparse matrix or not using the class and object approach.

Example:

```Input:
Enter Matrix elements :
[0][0]: 0
[0][1]: 1
[0][2]: 0
[1][0]: 1
[1][1]: 0
[1][2]: 1
[2][0]: 0
[2][1]: 1
[2][2]: 0
Output:
Entered Matrix :
0  1  0
1  0  1
0  1  0

It is a Sparse Matrix!
```

C++ code to check whether the matrix is a sparse matrix or not using the class and object approach

```#include <iostream>
using namespace std;

// create a class
class Matrix {
// private data member
private:
int matrix[3][3];

// public member funtions
public:
// getMatrix() funtion to insert matrix
void getMatrix() {
cout << "Enter Matrix elements :" << endl;
for (int row = 0; row < 3; row++) {
for (int column = 0; column < 3; column++) {
cout << "[" << row << "][" << column << "]: ";
cin >> matrix[row][column];
}
}
}

// sparseMatrix() funtion to check whether the
// matrix is a Sparse matrix or not
void sparseMatrix() {
// initialising int type variables
// to perform operations
int row, column, counter = 0;

cout << "\nEntered Matrix :" << endl;

// for loop to show the inserted matrix
for (row = 0; row < 3; row++) {
for (column = 0; column < 3; column++) {
cout << matrix[row][column] << "  ";
}
cout << "\n";
}

// nested for loop to traverse the whole matrix
for (row = 0; row < 3; row++) {
for (column = 0; column < 3; column++) {
// if condition to check for zero's in the matrix
if (matrix[row][column] == 0) {
counter++;
}
}
}

// if condition to check if the counter is greater than
// the total elements of the matrix
if ((counter > ((row * column) / 2))) {
cout << "\nIt is a Sparse Matrix!" << endl;
} else {
cout << "\nIt is not a Sparse Matrix!" << endl;
}
}
};

int main() {
// create an object
Matrix M;

// calling getMatrix() funtion
// to insert Matrix
M.getMatrix();

// calling sparseMatrix() funtion to check the matrix
// whether it is a Sparse matrix or not
M.sparseMatrix();

return 0;
}
```

Output

```Enter Matrix elements :
[0][0]: 1
[0][1]: 0
[0][2]: 1
[1][0]: 0
[1][1]: 1
[1][2]: 0
[2][0]: 1
[2][1]: 0
[2][2]: 1

Entered Matrix :
1  0  1
0  1  0
1  0  1

It is not a Sparse Matrix!
```

Explanation

In the above code, we have created a class Matrix, one int type 2d array data members matrix[3][3] to store the elements of the matrix, and public member functions getMatrix() and sparseMatrix() to store the matrix elements and to check whether the matrix is a sparse matrix or not.

In the main() function, we are creating an object M of class Matrix, reading the inputted matrix by the user using getMatrix() function, and finally calling the sparseMatrix() member function to check whether the matrix is a sparse matrix or not. The sparseMatrix() function contains the logic to check whether the matrix is a sparse matrix or not and printing the result.