-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSparseMatrixAddition.c
74 lines (70 loc) · 1.49 KB
/
SparseMatrixAddition.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include<stdio.h>
struct sparseTerm
{
int row;
int col;
int val;
};
int addSparce(struct sparseTerm A[],int Aterm,struct sparseTerm B[],int Bterm,struct sparseTerm C[])
{
int i=0,j=0,k=0;
while (i<Aterm && j<Bterm)
{
if (A[i].row==B[j].row && A[i].col==B[j].col )
{
C[k].row=A[i].row;
C[k].col=B[j].col;
C[k].val=A[i].val + B[j].val;
i++;j++;k++;
}
else if(A[i].row<B[j].row || (A[i].row == B[j].row && A[i].col < B[j].col))
{
C[k]=A[i];
i++;k++;
}
else
{
C[k]=B[j];
k++;j++;
}
}
while(i<Aterm)
{
C[k]=A[i];
i++;k++;
}
while(j<Bterm)
{
C[k]=B[j];
k++;j++;
}
return k;
}
void main()
{
struct sparseTerm A[20],B[20],C[20];
int Aterm,Bterm,Cterm,r,c;
printf("Enter the no. of the rows and columns of matrices: \n");
scanf("%d%d",&r,&c);
printf("Enter the no. non zero elements in matrices 1: \n");
scanf("%d",&Aterm);
printf("Enter the no. non zero elements in matrices 2: \n");
scanf("%d",&Bterm);
printf("Enter the rows columns and values for each non zero element in matrices 1: \n");
for (int i=0;i<Aterm;i++)
{
scanf("%d %d %d",&A[i].row,&A[i].col,&A[i].val);
}
printf("Enter the rows columns and values for each non zero element in matrices 2: \n");
for (int i=0;i<Bterm;i++)
{
scanf("%d %d %d",&B[i].row,&B[i].col,&B[i].val);
}
Cterm=addSparce(A,Aterm,B,Bterm,C);
printf("The Added matrix is \n");
printf("row\t|col\t|val\n");
for (int i=0;i<Cterm;i++)
{
printf("%d\t| %d\t| %d\t\n",C[i].row,C[i].col,C[i].val);
}
}