Adding Two Sparse Matrices-1
Adding Two Sparse Matrices-1
) Develop a C program to perform the following operations on sparse matrix using arrays and
functions
#include<stdio.h>
SparseTerm;
void addSparseMatrices(SparseTerm A[], int termsA, SparseTerm B[], int termsB, SparseTerm C[], int
*termsC);
int main()
else {
printSparseMatrix(C, termsC);
SparseTerm transposed[MAX_TERMS];
int termsTransposed;
printSparseMatrix(transposed, termsTransposed);
return 0;
}
scanf("%d", terms);
printf("Enter row, column, and value for term %d: ", i + 1);
void addSparseMatrices(SparseTerm A[], int termsA, SparseTerm B[], int termsB, SparseTerm C[], int
*termsC) {
int i = 0, j = 0, k = 0;
*termsC = 0;
C[k++] = A[i++];
else if (A[i].row > B[j].row || (A[i].row == B[j].row && A[i].col > B[j].col)) {
C[k++] = B[j++];
else {
C[k].row = A[i].row;
C[k].col = A[i].col;
C[k++].value = A[i].value + B[j].value; i++; j++;
C[k++] = A[i++];
C[k++] = B[j++];
*termsC = k;
int position[MAX_TERMS];
*termsB = 0;
rowTerms[A[i].col]++;
position[0] = 0;
B[pos].row = A[i].col;
B[pos].col = A[i].row;
B[pos].value = A[i].value;
if (rowTerms[i] > 0) {
(*termsB)++;
OUTPUT:
ALGORITHM:
Step 1:start
Step 2: Initialization:
Let A[] and B[] be the two sparse matrices in triplet form.
Let m be the number of non-zero elements in matrix A, and n be the number of non-zero elements
in matrix B.
i = 0, j = 0, and k = 0. The pointer i will traverse matrix A, j will traverse matrix B, and k will store the
position in result matrix C.
Case 1: If A[i] is before B[j] (either row or column is smaller), then: Copy A[i] to C[k].
Increment i and k.
Case 2: If B[j] is before A[i] (either row or column is smaller), then: Copy B[j] to C[k].
Increment j and k.
Case 3: If A[i] and B[j] are in the same position (same row and column): Add the values from
A[i] and B[j] and store the result in C[k]. Increment i, j, and k.
If any elements are left in A (i.e., i < m), copy all the remaining elements from A to C[]. If any
elements are left in B (i.e., j < n), copy all the remaining elements from B to C[].
The resulting matrix C[] now contains the sum of A and B in triplet form. Return C[] and the number
of non-zero elements in C (k).
Step 9:stop.