BCA/MCA Semester 2 : Data Structure Using C - Check Sparse Matrix
CHECK FOR SPARSE MATRIX
Answer:
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: