Matrix is a sparse matrix or not
C program to check whether a two dimensional array is a sparse matrix.
Any matrix is called a sparse matrix if most of its elements are zero. If the number of zeros (T) in a matrix exceeds (n*m)/2, where n, m is the dimension of the matrix, matrix is sparse matrix. Sparse matrix has more zero elements than nonzero elements.
T >= (n*m)/2
T >= (n*m)/2
Program
#include<stdio.h>
#include<conio.h>
#define MAX 10
void read_matrix(int mat[MAX][MAX], int row, int col)
{
int i, j;
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
printf("Element [%d][%d]\t:",i,j);
scanf("%d",&mat[i][j]);
}
}
}
void print_matrix(int mat[MAX][MAX], int row, int col)
{
int i, j;
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
printf("%d\t",mat[i][j]);
}
printf("\n");
}
}
void sparse(int mat[MAX][MAX], int row, int col)
{
int i, j, count;
count = 0;
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
if(mat[i][j] == 0)
{
count++;
}
}
}
if(count >= (row*col)/2)
{
printf("\nMatrix is a sparse matrix");
}
else
{
printf("\nMatrix is not a sparse matrix");
}
}
void main()
{
int mat[MAX][MAX];
int row, col;
printf("Enter the number of rows of the matrix\t:");
scanf("%d",&row);
printf("Enter the number of columns of the matrix\t:");
scanf("%d",&col);
printf("Enter the elements of the matrix\n");
read_matrix(mat, row, col);
printf("\nMatrix entered is\n");
print_matrix(mat, row, col);
sparse(mat, row, col);
getch();
}
Output
********** Run1 **********
Enter the number of rows of the matrix :3
Enter the number of columns of the matrix :4
Enter the elements of the matrix
Element [0][0] :1
Element [0][1] :2
Element [0][2] :0
Element [0][3] :0
Element [1][0] :0
Element [1][1] :3
Element [1][2] :4
Element [1][3] :0
Element [2][0] :0
Element [2][1] :5
Element [2][2] :0
Element [2][3] :0
Matrix entered is
1 2 0 0
0 3 4 0
0 5 0 0
Matrix is a sparse matrix
********** Run2 **********
Enter the number of rows of the matrix :3
Enter the number of columns of the matrix :4
Enter the elements of the matrix
Element [0][0] :1
Element [0][1] :2
Element [0][2] :3
Element [0][3] :4
Element [1][0] :5
Element [1][1] :0
Element [1][2] :0
Element [1][3] :0
Element [2][0] :6
Element [2][1] :5
Element [2][2] :6
Element [2][3] :0
Matrix entered is
1 2 3 4
5 0 0 0
6 5 6 0
Matrix is not a sparse matrix