sparse matrix C program
sparse matrix C program
#include<stdio.h>
int main()
{
int non_zeros=0;
int matrix[10][3];
int temp = 0;
int m,n,i,j,sparse_matrix[10][10];
//size of matrix
printf("Enter number of rows in the matrix : ");
scanf("%d",&m);
printf("Enter number of columns in the matrix : ");
scanf("%d",&n);
//read elements of matrix
printf("Enter elements in the matrix : ");
for ( i = 0; i < m; i++)
for ( j = 0; j < n; j++)
scanf("%d",&matrix[i][j]);
}
printf("\n");
}
// Step 2: Declare the 2-d array to store the compressed sparse matrix.
for ( i=0;i<m;i++)
{
for( j=0;j<n;j++)
{
if(matrix[i][j] != 0)
{
sparse_matrix[temp][0]=i;
sparse_matrix[temp][1]=j;
sparse_matrix[temp][2]=matrix[i][j];
temp++;
}
}
}// Sparse matrix is compressed.
printf(" \nThere are %d nonzero elements in matrix",non_zeros);
printf("\n------------------------------------------------------------\n");
printf("-------ROW NUMBER-----------COLUMN NUMBER----------VALUE----\n");
printf("------------------------------------------------------------\n");
for ( i=0;i<temp;i++)
{
printf("%15d %15d %15d \n",sparse_matrix[i][0], sparse_matrix[i][1],
sparse_matrix[i][2]);
}
printf("---------------------------------------------------------------- \n");
// Print the Compressed form of a sparse matrix.
getch();
return;
}