ADVANCED DATA STRUCTURES PROGRAM • LEVEL 10 — SPARSE MATRICES
Build Compressed Sparse Row Storage
Learn how to build compressed sparse row storage using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
No input required
Sample output
Values: 5 2 7 3 Columns: 1 0 3 2 RowStart: 0 1 3 4
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
int main(void)
{
int matrix[3][4] = {{0, 5, 0, 0}, {2, 0, 0, 7}, {0, 0, 3, 0}};
int values[12], columns[12], row_start[4], count = 0;
for (int row = 0; row < 3; row++) {
row_start[row] = count;
for (int column = 0; column < 4; column++) if (matrix[row][column]) { values[count] = matrix[row][column]; columns[count++] = column; }
}
row_start[3] = count;
printf("Values:"); for (int i = 0; i < count; i++) printf(" %d", values[i]);
printf("\nColumns:"); for (int i = 0; i < count; i++) printf(" %d", columns[i]);
printf("\nRowStart:"); for (int i = 0; i < 4; i++) printf(" %d", row_start[i]);
putchar('\n'); return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
Values: 5 2 7 3 Columns: 1 0 3 2 RowStart: 0 1 3 4
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Store non-zero values and columns contiguously while recording each row's start offset.
- Display the computed result.
Store non-zero values and columns contiguously while recording each row's start offset.
EFFICIENCY
Time and space complexity
Time complexity
O(rows * columns)
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.
