Sparse Matrix

Create a Sparse Matrix

#include<stdio.h>
#include<conio.h>
int main ()
{
	int i,j,a[10][10],sm[10][10],c=0,m,n;
   clrscr();
   printf("Enter the order of m x n matrix:\n");
   scanf("%d%d",&m,&n);
   printf("Enter the Matrix:\n");
   for(i=0;i<m;i++)
   	for(j=0;j<n;j++)
      	scanf("%d",&a[i][j]);
   //Calculation
   for(i=0;i<m;i++)
   {
   	for(j=0;j<n;j++)
      {
      	if(a[i][j]!=0)
          	c++;
      }
   }
   printf("\nNo of non zero element:%d\n\n",c);
   if(((m*n)/3)>c)
   {
   	printf("Sparse Matrix is:\n");
   	sm[0][0]=m;
   	sm[0][1]=n;
   	sm[0][2]=c;

   	for(i=0;i<m;i++)
   	{
   		for(j=0;j<n;j++)
      	{
      		if(a[i][j]!=0)
         	{
            	sm[i+1][0]=i+1;
            	sm[i+1][1]=j+1;
            	sm[i+1][2]=a[i][j];
         	}
      	}
   	}

   	//Printing
   	for(i=0;i<=c;i++)
   	{
   		for(j=0;j<3;j++)
      		printf("%d ",sm[i][j]);
      	printf("\n");
   	}
   }
   else
   	printf("It is not possible\n");
   getch();
   return 0;
}

Related posts:

Leave a Reply

Your email address will not be published. Required fields are marked *