Add two Sparse Matrix

#include
#include
int main ()
{
	int n,m,i,j,sp1[10][10],sp2[10][10],sp3[10][10],sp4[10][10],k=0;
   clrscr();
   printf("Enter the no of non-zero elements of SP1: ");
   scanf("%d",&m);
   printf("Enter the matrix SP1:\n");
   for(i=0;i<=m;i++)
   	for(j=0;j<3;j++)
      	scanf("%d",&sp1[i][j]);

   printf("Enter the no of non-zero elements of SP2: ");
   scanf("%d",&n);
   printf("Enter the matrix SP2:\n");
   for(i=0;i<=n;i++)
   	for(j=0;j<3;j++)
      	scanf("%d",&sp2[i][j]);

   if((sp1[0][0]==sp2[0][0])&&(sp1[0][1]==sp2[0][1]))
   {
      sp3[0][0]=sp1[0][0];
      sp3[0][1]=sp1[0][1];
      sp3[0][2]=sp1[0][2];
   	printf("Required Sparse Matrix is:\n\n");
      for(i=0;i<m;i++)
      {
         for(j=0;j<n;j++)
         {
        		if((sp1[i+1][0]==sp2[j+1][0])&&(sp1[i+1][1]==sp2[j+1][1]))
         	{
         		sp3[i+1][0]=sp1[i+1][0];
            	sp3[i+1][1]=sp1[i+1][1];
            	sp3[i+1][2]=sp1[i+1][2]+sp2[j+1][2];
               break;
            }
            else
            {
            	sp3[i+1][0]=sp1[i+1][0];
         		sp3[i+1][1]=sp1[i+1][1];
         		sp3[i+1][2]=sp1[i+1][2];
            }
         }

      }
      for(i=1;i<=n;i++)
      {

      	for(j=1;j<=m;j++)
         {
         	if((sp2[i][0]==sp3[j][0])&&(sp2[i][1]==sp3[j][1]))
            {
            	break;
            }
            else
            {
            	if(j==m)
               {
               	sp4[k][0]=sp2[i][0];
         			sp4[k][1]=sp2[i][1];
                  sp4[k][2]=sp2[i][2];
         			k++;
               }
               else
            		continue;
            }
         }
      }
      sp3[0][2]=m+k;
      for(i=0;i<=m;i++)
      {
   		for(j=0;j<3;j++)
      		printf("%d ",sp3[i][j]);
      	printf("\n");
      }
      for(i=0;i<k;i++)
      {
   		for(j=0;j<3;j++)
      		printf("%d ",sp4[i][j]);
      	printf("\n");
      }
   }
   else
   	printf("Addition can't possible!");
   getch();
   return 0;
}

Related posts:

Leave a Reply

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