
Think together · Start with a story
Three score cards show 4, 9, and 6. The robot treats the first one as the “current champion,” then takes on each challenge in turn.
Break down the process
- Start with 4Current maximum is 4
- Compare 9Update maximum to 9
- Compare 6Keep 9
To find the maximum, keep track of the largest value seen so far. Compare each new value and update it when needed.
01How do you find the largest number in a group?
Look at each number and keep track of the largest one you have seen so far.
02Step one: start by trusting the first element
int maximum = a[0];
For now, assume the maximum is 7.
03Step two: compare each value and update
for (int i = 1; i < 5; i++) {
if (a[i] > maximum) {
maximum = a[i];
}
}
max=7
No change
max=9
No change
04How do you find the smallest value?
Just reverse the comparison:
int minimum = a[0];
for (int i = 1; i < 5; i++) {
if (a[i] < minimum) {
minimum = a[i];
}
}
05Why not start the maximum at 0?
int a[3] = {-8, -2, -5};
If you write:
int maximum = 0;
the result will incorrectly be 0, even though 0 is not in the array.
06What about an empty array?
Ordinary C++ arrays usually need a positive number of elements when declared. But later, when using containers such as vector, you may encounter an empty sequence.
If there are no elements, there is no natural answer for “the maximum.” A program must handle the empty-data case first.
What you have learned
- To find the maximum, start with the first element as the current maximum.
- Then compare each value and update when you find a larger one.
- To find the minimum, reverse the comparison.
- Do not choose 0 as an initial value without a reason.
- If the data may be empty, handle the “no elements” case first.
Next: How Do You Find the Sum and Average of an Array?
Your turn to try
If the cards show -8, -3, and -6, can the maximum start at 0?
Ready? Open to see the explanation
That would incorrectly leave 0 as the maximum, even though it is not on any card. Start with the first value, -8, and the correct answer is -3.