Menu

1D Arrays

Finding highest and lowest values

To find the highest value in an array, keep a variable holding the highest value seen so far. Copy the first element into that variable, then compare each later element with it. If an element is larger, replace the stored value; if it is not, leave the stored value alone. After the last comparison, the variable holds the array's highest value.

The lowest value uses the same pattern. Copy the first element into a lowest-so-far variable, then replace it whenever a smaller element appears. Start with the first element rather than with 0, because 0 may not be a value in the array: it would be wrongly kept as the highest in an array of negative numbers, or as the lowest in an array of positive numbers.

Worked example

For the sunflower heights [132, 148, 121, 157], start both values at 132 and compare from index 1:

IndexValueHighest so farLowest so far
start132132132
1148148132
2121148121
3157157121

The final highest value is 157 and the final lowest value is 121.

heights = [132, 148, 121, 157]
highest = heights[0]
lowest = heights[0]
for i in range(1, len(heights)):
    if heights[i] > highest:
        highest = heights[i]
    if heights[i] < lowest:
        lowest = heights[i]
print("Tallest sunflower: " + str(highest))
print("Shortest sunflower: " + str(lowest))

Output:

Tallest sunflower: 157
Shortest sunflower: 121

The loop starts at index 1 because element 0 is already stored. It uses len(heights) as the stop value, so the same code works however many heights there are, without hard-coding 3.

Practise this