program on sparse addition and multiplication

FW: shristi sharma , 1BY13CS075


//program on sparse addition and multiplication
#include<stdio.h>
#include<conio.h>
typedef struct
{
int r;
int c;
int v;
}sparse;
sparse s1[20],s2[20],s3[20],s4[20];
int a[30][30], b[30][30], c[30][30], d[30][30];
void add();
void mul();
void print(int p[][30]);
void main()
{
int i;
clrscr();
printf("enter the size of row, column and value of sparse1 matrix\n");
scanf("%d%d%d",&s1[0].r,&s1[0].c,&s1[0].v);
for(i=1;i<=s1[0].v;i++)
{
scanf("%d%d%d",&s1[i].r,&s1[i].c,&s1[i].v);
a[s1[i].r][s1[i].c]=s1[i].v;
}
printf("enter the size of row, column and value of sparse2 matrix\n");
scanf("%d%d%d",&s2[0].r,s2[0].c,&s2[0].v);
for(i=1;i<=s2[0].v;i++)
{
scanf("%d%d%d",&s2[i].r,&s2[i].c,&s2[i].v);
b[s2[i].r][s2[i].c]=s2[i].v;
}
add();
mul();
printf("sparse 1:\n");
print(a);
printf("sparse 2:\n");
print(b);
printf("added sparse:\n");
print(c);
printf("multiplicated sparse:\n");
print(d);
getch();
}

void add()
{
int i,j;
if(s1[i].r!=s2[i].r||s1[i].c!=s2[i].c)
{
printf("addition not possible\n");
break;
}
for(i=0;i<s1[0].r;i++)
for(j=0;j<s1[0].c;j++)
{
c[i][j]=a[i][j]+b[i][j];
if(c[i][j]!=0)
{
s3[0].r=i;
s3[o].c=j;
s3[0].v=c[i][j];
}
}
}

void mul()
{
int i,j,k;
if(s1[o].c!=s2[0].r)
{
printf("multiplication is not possible\n");
break;
}
for(i=0;i<s1[0].r;i++)
for(j=0;j<s2[0].c;j++)
{
d[i][j]=0;
for(k=0;k<s1[0].c;k++)
{
d[i][j]=d[i][j]+(a[i][k]*b[k][j]);
if(d[i][j]!=0)
{
s4[0].r=i;
s4[0].c=j;
s4[0].v=d[i][j];
}
}
}
}

void print(int p[][30])
{
int i,j;
for(i=0;i<s1[0].r;i++)
{
for(j=0;j<s1[0].c;j++)
{
printf("%d",p[i][j]);
}
printf("\n");
}
}
Previous
Next Post »

Please Leave ur Valuable comments Here ConversionConversion EmoticonEmoticon

Facebook

HTML Comment Box is loading comments...

Our Partners

Our Partners