Let us learn how to find if a matrix is a sparse matrix in C programming language. This C code to check for sparse matrices makes use of Arrays.
However, a sparse matrix can also be represented in data structures using linked lists as well.
What is a Sparse Matrix?
A sparse matrix is a multi-dimensional array which consists of a higher number of zero elements.
In other words, a sparse matrix has a lower number of non-zero elements as compared to elements with zero as its value.
There are different algorithms used for storing sparse matrices. We have used static arrays for creating sparse matrices in the following code.
Example of Sparse Matrices
0 1 0
0 0 1
1 0 0
Find Sparse Matrix in C Programming using Arrays
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | #include <stdio.h> int main() { int matrix[25][25]; int i, j, rows, columns; int temp, zero_count = 0; printf("Enter the Number of Rows in Matrix:\t"); scanf("%d", &rows); printf("Enter the Number of Columns in Matrix:\t"); scanf("%d", &columns); printf("Enter the Matrix Elements\n"); for(i = 0; i < rows; i++) { for(j = 0; j < columns; j++) { printf("Element No.[%d][%d]:\t", i, j); scanf("%d", &matrix[i][j]); if(matrix[i][j] == 0) { zero_count = zero_count + 1; } } } printf("\nEntered Matrix\n"); for (i = 0; i < rows; i++) { for(j = 0; j < columns; j++) { printf("%d\t", matrix[i][j]); } printf("\n"); } temp = (rows * columns) / 2; if(zero_count > temp) { printf("\nThe Matrix is a Sparse Matrix with %d Zeros\n", zero_count); } else { printf("\nThe Matrix is Not a Sparse Matrix\n"); } return 0; } |
Output

In case you get any compilation errors or any doubts in this C program to check if a matrix is sparse or not, let us know about it in the comment section below.
Or we also can use else statement aftter if(matrix[i][j]==0)
Zero_count=Zero_count+1;
else
temp++;
Then we doesnot have to find the row*col/2;
And also got the number of non zero number in the matrix
Thanks. I thought that this program had some very difficult logi but it seems to be just so easy.