Example: If elements of the matrix is:
1 0 3
0 0 4
6 0 0
Output: Sparse matrix
Required knowledge:
Basic C programming, Fop loop, Array, MatrixSparse matrix:
Sparse matrix is a special matrix with most of its elements are zero. We can also assume that if (m * n) / 2 elements are zero then it is a sparse matrix.Algorithm to check sparse matrix:
To check whether a matrix is sparse matrix we only need to check the total number of elements that are equal to zero.If total number of elements equal to zero is defined by T then
T ≥ ((m * n) / 2 )
Program:
/** * C program to check sparse matrix */ #include <stdio.h> int main() { int A[3][3]; int row, col, total=0; /* * Reads elements in matrix from user */ printf("Enter elements in matrix of size 3x3: \n"); for(row=0; row<3; row++) { for(col=0; col<3; col++) { scanf("%d", &A[row][col]); } } /* * Counts total number of zero elements in the matrix */ for(row=0; row<3; row++) { for(col=0; col<3; col++) { /* * If the current element is zero */ if(A[row][col] == 0) { total++; } } } if(total >= (row * col)/2) { printf("\nThe given matrix is a Sparse matrix."); } else { printf("\nThe given matrix is not Sparse matrix."); } return 0; }
Output
Enter elements in matrix of size 3x3:
1 0 0
4 5 0
0 0 0
The given matrix is a Sparse matrix.
1 0 0
4 5 0
0 0 0
The given matrix is a Sparse matrix.
Happy coding ;)
You may also like
- Array and Matrix programming exercises index.
- C program to check Identity matrix.
- C program to check Symmetric matrix.
- C program to check whether two matrices are equal or not.
- C program to find transpose of a matrix.
- C program to find determinant of a matrix.
- C program to interchange diagonals of a matrix.
- C program to find sum of main diagonal elements of a matrix.
- C program to find sum of opposite diagonal elements of a matrix.
- C program to find sum of all array elements.
- C program to find maximum and minimum elements in an array.
- C program to count total number of duplicate elements in an array.
- C program to count total number of negative elements in an array.
- C program to count frequency of each element in an array.
- C program to print number in words.
- C program to print different star(*) patterns.