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.

AdvancedSparse representationTriplet form

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

ads-build-csr-sparse-matrix.c
Open in compiler
#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;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

Values: 5 2 7 3
Columns: 1 0 3 2
RowStart: 0 1 3 4
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Store non-zero values and columns contiguously while recording each row's start offset.
  3. 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.