Wednesday, 27 August 2014

SPARSE MATRIX

                            /* sparse matrix */

#include<stdio.h>
#include<conio.h>
int main()
{
int A[10][10],B[10][3],m,n,s=0,i,j;
printf("\nEnter the order m x n of the sparse matrix\n");
scanf("%d%d",&m,&n);
printf("\nEnter the elements in the sparse matrix(mostly zeroes)\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("\n%d row and %d column: ",i,j);
scanf("%d",&A[i][j]);
}
}
printf("The given matrix is:\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("%d ",A[i][j]);
}
printf("\n");
}
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
if(A[i][j]!=0)
{
B[s][0]=A[i][j];
B[s][1]=i;
B[s][2]=j;
s++;
}
}
}
printf("\nThe sparse matrix is given by");
printf("\n");
for(i=0;i<s;i++)
{
for(j=0;j<3;j++)
{
printf("%d ",B[i][j]);
}
printf("\n");
}
getch();
}



output
                                       
 Enter the order m*n of the sparse matrix
3
3
Enter the elements in the sparse matrix(mostly zeros)
0 row and 0 column 1
0 row and 1 column 1
0 row and 2 column 0
1 row and 0 column 0
1 row and 1 column 0
1 row and 2 column 10
2 row and 0 column 2
2 row and 1 column 2
2 row and 2 column 0
The given matrix is:
1 1 0
0 0 10
2 2 0
The sparse matrix is given by
1 0 0
1 0 1
10 1 2
2 2 0
2 2 1

No comments:

Post a Comment

Note: only a member of this blog may post a comment.