basics · intermediate · ~15 min
Find and fix an off-by-one — the kind of bug gdb helps you locate.
Find and fix an off-by-one bug — the kind of error gdb helps you pinpoint.
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.
A pointer a to n ints, and the count int n (n >= 0).
Returns the sum of the n elements, as an int.
sum_array({1,2,3,4}, 4) -> 10
sum_array({5}, 1) -> 5
0..n-1; never read a[n].<= should be <) — keep the rest correct.A pointer a to n ints, and the count int n (n >= 0).
The sum of the n elements, as an int.
Sum exactly indices 0..n-1; do not read a[n].
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.