C Tutorial
In numerical analysis, a sparse matrix is a matrix in which most of the elements are zero.
Let us see example 4x4 sparse matrix,
1 1 0 0 0 1 0 0 0 0 1 0 0 1 0 1
This c program is used to check whether the user input matrix is sparse matrix or not.
This program is implementd using two dimensional array for matrix data and validating sparse matrix logic is done using nested for loops.
A sparse matrix is a matrix in which most of the elements are zero.
#include<stdio.h> #define COLUMN 10 #define ROW 10 void main() { int matrix[ROW][COLUMN]; int i,j, rows, columns, zeroscount=0, nonzeroscount=0; printf("\nEnter Matrix Rows: "); scanf("%d", &rows); printf("\nEnter Matrix Columns: "); scanf("%d", &columns); printf("\nEnter Matrix: \n"); for(i=0;i<rows;i++) { for(j=0;j<columns;j++) { scanf("%d", &matrix[i][j]); } } for(i=0;i<rows;i++) { for(j=0;j<columns;j++) { if(matrix[i][j]==0) { zeroscount++; } else { nonzeroscount++; } } } if(zeroscount>nonzeroscount) { printf("\nUser input matrix is a sparse matrix!\n"); } else { printf("\nUser input matrix is not a sparse matrix!\n"); } }
Output:
$ cc sparse_matrix.c $ ./a.out Enter Matrix Rows: 3 Enter Matrix Columns: 3 Enter Matrix: 1 0 0 0 0 1 1 0 0 User input matrix is a sparse matrix! $ ./a.out Enter Matrix Rows: 3 Enter Matrix Columns: 3 Enter Matrix: 1 1 1 0 1 1 1 1 0 User input matrix is not a sparse matrix!
C Tutorial
Privacy Policy | Copyright2020 - All Rights Reserved. | Contact us
| Report website issues in Github
| Facebook page
| Google+ page