← Exercises|

Finding the largest, and where

Write12 of 14 · about 8 min

Finding the largest, and where

An array passed to a function decays into a pointer to its first element. The function has no way to find out how long it is — sizeof inside the function gives the size of a pointer, not the array. So the length has to be a second parameter. Every C function that takes an array does this.

Start a maximum from the first element, not from 0: an array of negative numbers has no element above 0, and the answer would come back wrong with no sign that anything happened.

Returning more than one value means passing an address to write into — the same rule as the swap exercise.

Example

int total(const int *values, int count) {
    int sum = 0;
    for (int i = 0; i < count; i++) {
        sum += values[i];
    }
    return sum;
}

values[i] and *(values + i) are the same thing. The brackets are the friendlier spelling.

Your task

Write int max_of(const int *values, int count, int *index_out): return the largest value and store the index where it was found through index_out. On the first largest value if there are ties. count is at least 1.

Stuck?

Explain it

What goes wrong if you start best at 0 instead of values[0]?

Not graded — this is for you.

Where this goes

Project 7 builds a statistics tool over arrays. max_of is the first function it asks for, and the ties and negative cases are in its rubric.