Plan for Maximum
Calculating the largest value in the array, the maximum, will require the logic be adjusted to use the for each style. How do you identify the largest value in a list of numbers? With a small list you are likely to just quickly scan it and see the largest value. The computer cannot do this! We need to think about simple actions the computer can perform to achieve this. Maybe think about how you would do it for a very long list of numbers, one that spans across many pages.
The algorithm needed to find the maximum value in an array needs to perform an action for each element of the array. It needs to process each value in isolation, ignoring the other values from the list as you process that one element.
The key is similar to the logic from sum
. You need to keep a running maximum. This will store the current maximum from the array as you loop through each element. Like the sum, this value can be updated within the loop and should be correct at the end.
Have a go at thinking through the logic for this.
-
The pseudocode I came up with is shown below. Notice that its basic layout if the same as in
sum
. It initialises themax
value and then loops through the array performing an action for each value. In this case the action is to check if the i th value of the array is larger than the running maximum in themax
variable. When this is the case a new maximum has been found and is stored in themax
variable.One of the important differences between
maximum
andsum
is the initialisation of themax
value at the start. Inmaximum
this cannot be initialised to 0.Can you think of a case where initialising this to 0 would fail?
What would happen if all values in the array were negative? In this case the function would return 0 as the maximum, even though 0 is not a value in the array.
To address this, we need to make sure that the maximum is a value from the array. We can do this by initialising the
max
with the first value in the array. The for loop can then start looping from the 2 nd element, as the 1 st has already been processed.Notice how the idea is the same as with the earlier functions. You need to think of the logic in a way that can work by processing each element of the array one at time. Additional variables, such as the sum or max, can be added to help you remember values as you go step through the elements in the array.
Once you have a plan, code it up and test it out. Try with all positive, and all negative values as well as with no values at all.