AP® Computer Science A · Unit 2 · Topic 2.9

Finding a Maximum or Minimum in a Loop

Finding a max in a loop means keeping a running champion value that only gets replaced when something bigger shows up, so by the end of the array it has beaten every challenger.

A computer never sees the whole array at once. It sees one element at a time and remembers one thing: the best value found so far. Set max equal to the first element, then walk through the rest of the array one by one. At each stop, compare the current element to max. If the current element is bigger, it becomes the new max. If not, max stays exactly as it is and the loop moves on. By the time the loop ends, max has silently been compared against every element and survived every challenge, so it must be the largest value in the whole array.

Think of it like a running champion in a tournament. The first contestant to step up is champion by default. Every new contestant only takes the title if they actually beat the current champion — ties and losses change nothing. This is why initialization matters so much: start max at the array's own first element, not at some arbitrary number like 0. If the array is full of negative numbers, nothing will ever exceed 0, and the loop will report a maximum that was never actually in the data. Minimum works the same way in reverse: start min at the first element and replace it only when something smaller appears.

This idea sits right next to other loop patterns like running totals and counting matches — all three share the same shape of initialize, then update once per pass. The variation worth noticing is tracking position instead of value: keep an index variable, update it alongside max whenever a new champion is found, so after the loop you know not just how large the maximum is but exactly where it lives in the array.

Key terms

running maximum
A variable that holds the largest value seen so far as a loop moves through a collection.
initialization
Setting a variable's starting value before a loop begins, often to the first element itself.
trace table
A table showing how each variable's value changes on every pass of a loop.
index tracking
Storing the position of the current best value alongside the value itself, usually to report where it occurs.

Watch it explained

  1. How it worksHow does a running champion get replaced only when something bigger turns up?
  2. Worked exampleTrace the running maximum through 5, 12, 3, 19, 7 and mark every replacement.
  3. Common mistakeWhy doesn't starting the maximum at 0 work when the values can be negative?
  4. Going furtherWhat changes when you also need the position of the largest value, not just the value?

Check yourself

Your turn1 of 2
Starting a running maximum at 35, the loop then compares it to 33. What is the running maximum after this comparison?

End of topic.