basics · intermediate · ~15 min

Fix the array sum (off-by-one)

Find and fix an off-by-one — the kind of bug gdb helps you locate.

Challenge

The starter has a bug: it reads one element past the array. Fix int sum_array(const int *a, int n) so it correctly sums exactly n elements.

Starter code

int sum_array(const int *a, int n) {
    int s = 0;
    for (int i = 0; i <= n; i++)  /* BUG: <= reads a[n] */
        s += a[i];
    return s;
}

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.