Hi! Here's my code for addition of two sparse matrices represented as a 3-tuple. The program adds up all elements in sparse matrices A and B and stores it in matrix C except that it repeats some elements. How should the code be modified?
Here's my code:
Code:
#include<stdio.h>
#include<conio.h>
int main(void)
{
int a[20][3],b[20][3],c[40][3],i,j,k=1,count=0,m;
printf("Enter non zero elements of s matrix 1:"); //accept matrix A directly in the 3-tuple form
scanf("%d",&a[0][2]);
printf("\nEnter matrix:");
for(i=0;i<=a[0][2];i++)
{
for(j=0;j<3;j++)
{
scanf("%d%",&a[i][j]);
}
}
printf("\nEnter non zero elements of s matrix 2:"); //accept matrix B directly in the 3-tuple form
scanf("%d",&b[0][2]);
printf("\nEnter matrix:");
for(i=0;i<=b[0][2];i++)
{
for(j=0;j<3;j++)
{
scanf("%d%",&b[i][j]);
}
}
//init all elements of matrix C to zero(required for the check made below at *)
for(i=0;i<20;i++)
{
for(j=0;j<3;j++)
{
c[i][j]=0;
}
}
//copy elements from matrices A and B with the same indices into the corresponding index of C
for(i=1;i<=a[0][2];i++)
{
if(a[i][0]==b[i][0] && a[i][1]==b[i][1])
{
c[k][0]=a[i][0];
c[k][1]=a[i][1];
c[k][2]=a[i][2]+b[i][2];
count++;
}
}
//copy uncommon elements from A to matrix C
for(i=1;i<=a[0][2];i++)
{
LOOP:if(c[k][2]==0) //* CHECK c[k][2] if it has been modified. If it has, there will be some non zero value.
{ //if c[k][2]=0, then there is no data in C at that location.So we may copy current element of A
//into C.. (same for matrix B below..)
c[k][0]=a[i][0];
c[k][1]=a[i][1];
c[k][2]=a[i][2];
count++;
k++;
continue;
}
else
{
k++;
goto LOOP;
}
}
//copy uncommon from B to matrix C
k=1;
for(i=1;i<=b[0][2];i++)
{
LOOP2:if(c[k][2]==0) //* check c[k][2] if it has been modified. If it has, there will be some non zero value.
{
c[k][0]=b[i][0];
c[k][1]=b[i][1];
c[k][2]=b[i][2];
k++;
count++;
continue;
}
else
{
k++;
goto LOOP2;
}
}
c[0][2]=count;
c[0][0]=a[0][0];
c[0][1]=a[0][1];
//print matrix C
printf("\n\nAddition is:");
for(i=0;i<=c[0][2];i++)
{
printf("\n");
for(j=0;j<3;j++)
{
printf(" %d ",c[i][j]);
}
}
getch();
return 0;
}