1D Arrays
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.
For the sunflower heights [132, 148, 121, 157], start both values at 132 and compare from index 1:
| Index | Value | Highest so far | Lowest so far |
|---|---|---|---|
| start | 132 | 132 | 132 |
| 1 | 148 | 148 | 132 |
| 2 | 121 | 148 | 121 |
| 3 | 157 | 157 | 121 |
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: 121The 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.
OCR GCSE Computer Science · 1D Arrays