Sparse Matrix Addition & Multiplication

#include<stdio.h>
#include<conio.h>
#include<alloc.h>
#define CALLOC(p,n,type)\
p=(type*)calloc(1,n*sizeof(type));\

int **a,**b,**d,**m;
typedefstruct
{
int r;
int c;
int v;
}sp;
sp s[10];
void read()
{
inti,j,k,csum;
printf("\nenterrow,col,val of non-zero elements of 'A' ");
for(i=1;i<=s[0].v;i++)
 {
scanf("%d,%d,%d",&s[i].r,&s[i].c,&s[i].v);
 *(a[s[i].r]+s[i].c) = s[i].v;
 }
printf("\nenterrow,col,val of non-zero elements of 'B' ");
for(i=1;i<=s[0].v;i++)
 {
scanf("%d,%d,%d",&s[i].r,&s[i].c,&s[i].v);
 *(b[s[i].r]+s[i].c)=s[i].v;
  }
for(i=0;i<s[0].r;i++)
for(j=0;j<s[0].c;j++)
 *(d[i]+j)=*(a[i]+j)+ *(b[i]+j);
for(i=0;i<s[0].r;i++)
 {
for(j=0;j<s[0].c;j++)
   {
csum=0;
for(k=0;k<s[0].c;k++)
      {
csum= csum+(*(a[i]+k))*(*(b[k]+j));
      }
     *(m[i]+j)=csum ;
   }
 }
}
void display()
{
inti,j;
printf("\n Sparse matrix A=\n");
for(i=0;i<s[0].r;i++)
 {
for(j=0;j<s[0].c;j++)
printf("%d ",*(a[i]+j));
printf("\n");
 }
printf("\n Sparse matrix B=\n");
for(i=0;i<s[0].r;i++)
 {
for(j=0;j<s[0].c;j++)
printf("%d ",*(b[i]+j));
printf("\n");
 }
printf("\n Sum of A and B =\n");
for(i=0;i<s[0].r;i++)
 {
for(j=0;j<s[0].c;j++)
printf("%d ",*(d[i]+j));
printf("\n");
 }
printf("\nproduct of A and B=\n");
for(i=0;i<s[0].r;i++)
 {
for(j=0;j<s[0].c;j++)
printf("%d ",*(m[i]+j));
printf("\n");
 }

}
void main()
{
inti,j;
clrscr();
printf("\nenterRxC ");
scanf("%dx%d",&s[0].r,&s[0].c);
printf("\nenter number of non-zero elements ");
scanf("%d",&s[0].v);
CALLOC(a,s[0].r,int *);
CALLOC(b,s[0].r,int *);
CALLOC(d,s[0].r,int *);
CALLOC(m,s[0].r,int *);
for(i=0;i<s[0].c;i++)
 {
CALLOC(a[i],s[0].c,int);
CALLOC(b[i],s[0].c,int);
CALLOC(d[i],s[0].c,int);
CALLOC(m[i],s[0].c,int);
  }
read();
display();
getch();
}


Note: Compiler to be used are TurboC/Dev C++/C7dos

For deeper understanding of Sparse matrix do refer the E book below 
Feedbacks and Suggestions are welcome ....



Previous
Next Post »

Please Leave ur Valuable comments Here ConversionConversion EmoticonEmoticon

Facebook

HTML Comment Box is loading comments...

Our Partners

Our Partners