ADVANCED DATA STRUCTURES PROGRAM • LEVEL 10 — SPARSE MATRICES
Multiply Two Sparse Matrices
Learn how to multiply two sparse matrices using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
No input required
Sample output
0 16 15 0
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
int main(void)
{
int first[2][3] = {{1, 0, 2}, {0, 3, 0}};
int second[3][2] = {{0, 4}, {5, 0}, {0, 6}};
for (int row = 0; row < 2; row++) {
for (int column = 0; column < 2; column++) {
int sum = 0;
for (int index = 0; index < 3; index++) if (first[row][index] && second[index][column]) sum += first[row][index] * second[index][column];
printf("%d%c", sum, column == 1 ? '\n' : ' ');
}
}
return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
0 16 15 0
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Skip zero products while accumulating compatible row-column pairs.
- Display the computed result.
Skip zero products while accumulating compatible row-column pairs.
EFFICIENCY
Time and space complexity
Time complexity
O(rows * columns * shared)
Auxiliary space
O(non-zero elements)
DEBUGGING CHECKLIST
Common mistakes
Check this
Use the correct format specifier for every variable.
Check this
Initialize variables before using their values.
Check this
Check braces, semicolons and input order carefully.
Try it yourself
Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.
