0% found this document useful (0 votes)
25 views

sparse matrix C program

The document provides a C program for representing a sparse matrix using a two-dimensional array. It prompts the user to input the dimensions and elements of the matrix, counts the non-zero elements, and stores the non-zero entries in a compressed format. Finally, it displays the row number, column number, and value of each non-zero element in the sparse matrix.

Uploaded by

Prafulla BCA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

sparse matrix C program

The document provides a C program for representing a sparse matrix using a two-dimensional array. It prompts the user to input the dimensions and elements of the matrix, counts the non-zero elements, and stores the non-zero entries in a compressed format. Finally, it displays the row number, column number, and value of each non-zero element in the sparse matrix.

Uploaded by

Prafulla BCA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

/*

* Sparse Matrix Representation in C Using a Two-dimensional Array


*/

#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]);

// Step 1: Count the number of non-zeros in the sparse matrix.


printf("\n Matrix is \n");
for ( i=0;i<m;i++)
{
for(j=0;j<n;j++)
{ printf("%d\t",matrix[i][j]) ;
if(matrix[i][j] != 0)
{
non_zeros++;
}

}
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;
}

You might also like