Array Exercises
Write a C program to read elements in a matrix and check whether matrix is Sparse matrix or not. C program for determining sparse matrix. How to check sparse matrix in C. Logic to check sparse matrix in C programming.
Required knowledge
Basic C programming, C for loop, ArrayS
What is Sparse 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.
Logic 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. The matrix is sparse matrix if T ≥ ((m * n) / 2 ); where T defines total number of zero elements.

Program to check sparse matrix
/** * C program to check sparse matrix */ #include <stdio.h> #define SIZE 3 int main() { int A[SIZE][SIZE]; int row, col, total=0; /* Input elements in matrix from user */ printf("Enter elements in matrix of size 3x3: \n"); for(row=0; row<SIZE; row++) { for(col=0; col<SIZE; col++) { scanf("%d", &A[row][col]); } } /* Count total number of zero elements in the matrix */ for(row=0; row<SIZE; row++) { for(col=0; col<SIZE; 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 6 0
0 0 0
4 0 5
The given matrix is a Sparse matrix.
Process returned 0 (0x0) execution time : 33.630 s
Program to check sparse matrix
/** * C program to check sparse matrix */ #include <stdio.h> int main() { int A[10][10]; int row, col, total=0,n; printf("Enter size of matrix:"); scanf("%d",&n); /* Input elements in matrix from user */ printf("Enter elements in matrix of size 3x3: \n"); for(row=0; row<n; row++) { for(col=0; col<n; col++) { scanf("%d", &A[row][col]); } } /* Count total number of zero elements in the matrix */ for(row=0; row<n; row++) { for(col=0; col<n; 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; }