15.7. Finding the Largest or Smallest Value

Another common pattern for working with lists is finding the largest or smallest value. We saw an example of code to do this earlier, but let’s break down the important parts of this recipe.

We need to have a “tracking variable” that will store the largest (or smallest value we have seen). The easiest way to initialize that variable is to use the first value from the list (index 0). When we are starting, the first value is the largest (or smallest) we have seen.

We then loop through the values and compare each to the highest value. If the current value is higher than the largest we have seen (or smaller than the lowest), we change our tracking variable to hold that new “best” value.

This program is designed to find the highest value. It works correctly - you can run watch it run in code lab to see step by step how it does its job.

Modify it to find the lowest value:

  • Change the tracking variable’s name to lowest

  • Change the comparison used in the if. If the current score is lower then the lowest, we have found a new lowest value.

Note

If we are not sure that the list has any items, we can’t start with the first item. In that case we can start with some value that is so low (or high as appropriate) we are confident the first item we do look at will be “better” and replace the starting one.

The program above could use 0 as the initial value for highest - the first value we see would be sure to be higher. But once we change the program to look for the lowest, we would have to change the starting value to 101 or something large to guarantee that any real values we looked at would be lower.

This is trickier to get right than just starting with the first value, so we won’t need it unless we have to.

Sometimes the max or min pattern might need to be modified to work with values calculated from each item. Here is an example of adapting the basic recipe to find the longest name in a list of names:

You have attempted of activities on this page