This is a C++ Program to Find if an Array is a Sparse Matrix.
The program takes an array and checks if it is a sparse matrix. A sparse matrix is a matrix which has maximum elements equal to 0.
1. The program takes the number of rows and columns of the matrix.
2. Then the elements are entered.
3. If the matrix contains maximum number of elements as 0, then it is a sparse matrix.
4. Else not.
5. The result is printed.
6. Exit.
Here is the source code of C++ Program to Find if an Array is a Sparse Matrix. The program output is shown below.
#include<iostream>
using namespace std;
int main ()
{
int A[10][10], i, j, m, n, count = 0;
cout << "Enter number of rows and columns : ";
cin >> m >> n;
cout << "Enter array elements : ";
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
cin >> A[i][j];
if (A[i][j] == 0)
count++;
}
}
if (count > ((m * n) / 2))
cout << "The matrix is a sparse matrix.\n ";
else
cout << "The given matrix is not a sparse matrix.\n ";
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
cout << A[i][j] << " ";
cout << "\n ";
}
return 0;
}
1. The user is asked to enter the number of rows and columns.
2. The elements are then asked to enter and stored in the matrix ‘A’.
3. If the element entered is 0, a variable ‘count’ is incremented.
4. If count is greater than half the total size of the matrix, then the matrix is a sparse matrix.
5. Else the entered array is not a sparse matrix.
6. The result is then printed.
Case 1 : Enter number of rows and columns : 3 3 Enter array elements : 1 0 2 0 3 0 4 0 5 The given matrix is not a sparse matrix. 1 0 2 0 3 0 4 0 5 Case 2 : Enter number of rows and columns : 1 3 Enter array elements : 0 10 0 The matrix is sparse matrix. 0 10 0 Case 3 : Enter number of rows and columns : 3 3 Enter array elements : 1 0 0 0 2 0 0 0 3 The matrix is a sparse matrix. 1 0 0 0 2 0 0 0 3
Sanfoundry Global Education & Learning Series – C++ Programs.
To practice all C++ programs, here is complete set of 1000+ C++ Programming examples.
- Apply for C++ Internship
- Check C++ Books
- Apply for Computer Science Internship
- Check Computer Science Books
- Check Programming Books