basics · intermediate · ~15 min

Fix the maximum (bad initial value)

Spot an initialisation bug that only shows on certain inputs.

Challenge

Fix an initialisation bug that only surfaces on certain inputs.

Task

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.

Input

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

Output

Returns the largest element, as an int.

Example

find_max({-5,-2,-9}, 3)   ->   -2
find_max({3,7,1}, 3)      ->   7

Edge cases

  • All-negative arrays must return the largest negative value, not 0.

Rules

  • Seed the running maximum from a real element (a[0]), not from 0.

Input format

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

Output format

The largest element, as an int.

Constraints

n >= 1; initialise the max from a[0], not 0.

Starter code

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.