# Check Sparse Matrix C Program

## C Program To Check Sparse Matrix using Arrays

Learn How To Find if a Matrix is a Sparse Matrix or not 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 higher number of **Zero **elements. In other words, a sparse matrix has 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**

#### C Program To Find Sparse Matrix 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.