ADVANCED DATA STRUCTURES PROGRAM • LEVEL 10 — SPARSE MATRICES

Calculate Row Sums from Sparse Triplets

Learn how to calculate row sums from sparse triplets using a clear C program.

IntermediateSparse representationTriplet form

PROBLEM UNDERSTANDING

Input and expected output

Sample input
No input required
Sample output
5 9 3

COMPLETE C PROGRAM

Complete C implementation

ads-sparse-matrix-row-sums.c
Open in compiler
#include <stdio.h>

int main(void)
{
    int triplets[][3] = {{0, 1, 5}, {1, 0, 2}, {1, 3, 7}, {2, 2, 3}};
    int sums[3] = {0};
    for (int index = 0; index < 4; index++) sums[triplets[index][0]] += triplets[index][2];
    printf("%d %d %d\n", sums[0], sums[1], sums[2]);
    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

5 9 3
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Accumulate each stored value into the total for its triplet row.
  3. Display the computed result.

Accumulate each stored value into the total for its triplet row.

EFFICIENCY

Time and space complexity

Time complexity

O(non-zero)

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.