basics · intermediate · ~15 min
Spot an initialisation bug that only shows on certain inputs.
Fix an initialisation bug that only surfaces on certain inputs.
The starter code for int find_max(const int *a, int n) is meant to return the largest element, but it initialises the running maximum to 0. That is wrong for all-negative arrays (it would return 0 instead of the real maximum). Fix it to seed the maximum from a[0] so it works for any inputs. You may assume n >= 1. No main — the grader calls it.
A pointer a to n ints, and the count int n (n >= 1).
Returns the largest element, as an int.
find_max({-5,-2,-9}, 3) -> -2
find_max({3,7,1}, 3) -> 7
a[0]), not from 0.A pointer a to n ints, and the count int n (n >= 1).
The largest element, as an int.
n >= 1; initialise the max from a[0], not 0.
int find_max(const int *a, int n) {
int m = 0; /* BUG: wrong for all-negative arrays */
for (int i = 0; i < n; i++)
if (a[i] > m) m = a[i];
return m;
}
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.