Section 27.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.
Checkpoint 27.7.1.
This program is designed to find the highest value. It works correctly - you can watch it run in codelens 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 than the lowest
, we have found a new lowest value.
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.