Lab Program 7
Lab Program 7
CODE
#include <stdio.h>
#include <stdlib.h>
// Function to add the specified value to the existing value at the specified row
and column
void addValue(SparseMatrix* mat, int row, int col, int value) {
Node* current = mat->rowsArray[row];
while (current != NULL) {
if (current->col == col) {
current->value += value;
return;
}
current = current->next;
}
// If the element does not exist, create a new node with the specified value
setValue(mat, row, col, value);
}
// Function to multiply each element of the sparse array by the specified scalar
factor
void multiplyScalar(SparseMatrix* mat, int factor) {
for (int i = 0; i < mat->rows; i++) {
Node* current = mat->rowsArray[i];
while (current != NULL) {
current->value *= factor;
current = current->next;
}
}
}
// Example usage
int main() {
SparseMatrix* mat1 = createSparseMat(3, 4);
setValue(mat1, 0, 0, 1);
setValue(mat1, 0, 2, 2);
setValue(mat1, 1, 1, 3);
setValue(mat1, 2, 3, 4);
addValue(mat1, 1, 1, 2);
printf("\nAfter adding 2 to (1, 1):\n");
printSparseMat(mat1);
removeValue(mat1, 0, 0);
printf("\nAfter removing (0, 0):\n");
printSparseMat(mat1);
multiplyScalar(mat1, 2);
printf("\nAfter multiplying by 2:\n");
printSparseMat(mat1);
add(mat1, mat2);
printf("\nAfter adding Sparse Matrix 2 to Sparse Matrix 1:\n");
printSparseMat(mat1);
return 0;
}
OUTPUT
Sparse Matrix 1:
(0, 2, 2) (0, 0, 1)
(1, 1, 3)
(2, 3, 4)
(1, 1, 5)
(2, 0, 2)
(3, 2, 4)
After multiplying by 2:
(0, 2, 4)
(1, 1, 10)
(2, 3, 8)
Sparse Matrix 2:
(0, 1, 1)
(1, 0, 2)
(2, 2, 3)
(3, 1, 4)
Matrix dimensions do not match for addition