# IP University Musings BCA, MCA, BBA, MBA, BTech Question Papers and Study Notes

## CHECK FOR SPARSE MATRIX

Data Structure Using C

Question: Write a program in 'C' to check whether a matrix is a sparse matrix or not.

A sparse matrix is a matrix in which the most of the elements are zero (0). Here follows a program which inputs matrix elements and checks if more than half of its elements are zero, it is a sparse matrix.

```/*
* C Program to check whether a matrix is Sparse Matrix
*/

#include <stdio.h>

int main(){
int rows, cols, row, col, count=0;
int matrix[50][50];

printf("Enter Rows and Columns of Matrix\n");
scanf("%d %d", &rows, &cols);

printf("Enter Matrix of size %dX%d\n", rows, cols);

for(row = 0; row < rows; row++){
for(col = 0; col < cols; col++){
scanf("%d", &matrix[row][col]);
}
}

/* Print the matrix */
printf("Matrix is:\n");
printf("⎡");
for(col = 0; col < cols; col++)
printf("\t");
printf("⎤\n");

for(row = 0; row < rows; row++){
printf("⎢ ");
for(col = 0; col < cols; col++){
printf("%3d\t", matrix[row][col]);
}
printf("⎥");
printf("\n");
}
printf("⎣");
for(col = 0; col < cols; col++)
printf("\t");
printf("⎦\n");

/* Count the number of Zero's(0) in Matrix */
for(row = 0; row < rows; row++){
for(col = 0; col < cols; col++){
if(matrix[row][col] == 0){
count++;
}
}
}

if(count > (rows*cols)/2){
printf("Input Matrix is a Sparse Matrix\n");
} else {
printf("Input Matrix is Not a Sparse Matrix\n");
}

return 0;
}
```

Compile the program in bash shell.  and run its compiled out.
\$ gcc sparsecheck.c -o sparsecheck.out
\$ ./sparsecheck.out

Here is the output:

Share:

## BCE-Hacks Notes

Chemical Engineering Notes

Maths Resources

Geography Quiz

Developer-Bytes

## History MCQs

History Quiz For Competitive exams

Developer Bytes