This is a C program to check whether a matrix is sparse matrix or not. A matrix is sparse matrix, if more than half of the elements of a matrix is zero.
This program traverse the given matrix row wise using two for loop and count the number of zero's in the matrix. If count of zero elements is more that half of total elements the given matrix is a sparse matrix otherwise not a sparse matrix.
Required Knowledge
C Program to find a matrix is sparse matrix or not
#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]); } } /* 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; }Output
Enter Rows and Columns of Square Matrix 3 3 Enter Matrix of size 3X3 3 2 0 0 3 0 0 0 1 Input Matrix is a Sparse Matrix
Enter Rows and Columns of Square Matrix 3 3 Enter Matrix of size 3X3 1 2 3 4 5 0 0 6 7 Input Matrix is Not a Sparse Matrix
Related Topics