In this tutorial, i am going to show you how to check matrix is a sparse matrix in c programs.

## Algorithm to Check Matrix is a Sparse Matrix

Follow the below given algorithm to write a program to check whether a matrix is sparse or not; as follows:

- Start Program.
- Declare and initialize a matrix of m*n. (where m and n are the lengths of row and column of matrix)
- Take input Rows and Columns Number From User.
- Take input matrix elements from user using for loop.
- Declare a variable to count the number zeros in the matrix. (Consider “count”).
- Travers the matrix from start to end and whenever zero encounter increment
**count by 1**. - if the
**count**is greater than**m*n/2**then the matrix is sparse, else it is not. - Print Result.
- End Program.

## C Program to Check Matrix is a Sparse Matrix

/* C Program to check Matrix is a Sparse Matrix or Not */ #include<stdio.h> int main() { int i, j, rows, columns, a[10][10], Total = 0; printf("\n Please Enter Number of rows and columns : "); scanf("%d %d", &i, &j); printf("\n Please Enter the Matrix Elements \n"); for(rows = 0; rows < i; rows++) { for(columns = 0;columns < j;columns++) { scanf("%d", &a[rows][columns]); } } for(rows = 0; rows < i; rows++) { for(columns = 0; columns < j; columns++) { if(a[rows][columns] == 0) { Total++; } } } if(Total > (rows * columns)/2) { printf("\n The Matrix that you entered is a Sparse Matrix "); } else { printf("\n The Matrix that you entered is Not a Sparse Matrix "); } return 0; }

The result of the above c program; as follows:

Please Enter Number of rows and columns : 3 3 Please Enter the Matrix Elements 1 2 3 4 5 6 7 8 9 The Matrix that you entered is Not a Sparse Matrix

## Be First to Comment