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

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

Task

The starter code for int sum_array(const int *a, int n) is meant to return the sum of the first n elements, but it has a bug: its loop condition i <= n reads one element past the end (a[n]). Fix it so it sums exactly the n valid elements (indices 0..n-1). No main — the grader calls it.

Input

A pointer a to n ints, and the count int n (n >= 0).

Output

Returns the sum of the n elements, as an int.

Example

sum_array({1,2,3,4}, 4)   ->   10
sum_array({5}, 1)         ->   5

Edge cases

  • Valid indices run 0..n-1; never read a[n].

Rules

  • The fix is to change the loop bound (<= should be <) — keep the rest correct.

Input format

A pointer a to n ints, and the count int n (n >= 0).

Output format

The sum of the n elements, as an int.

Constraints

Sum exactly indices 0..n-1; do not read a[n].

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.