Question 1 Report
Study the following pseudocode that finds the maximum value in an array.
DECLARE Scores : ARRAY[1:8] OF INTEGER
DECLARE MaxScore : INTEGER
DECLARE MaxPos : INTEGER
MaxScore <- Scores[1]
MaxPos <- 1
FOR Index <- 2 TO 8
IF Scores[Index] > MaxScore
THEN
MaxScore <- Scores[Index]
MaxPos <- Index
ENDIF
NEXT Index
OUTPUT "Highest score: ", MaxScore, " at position ", MaxPos
The array Scores contains: 45, 72, 38, 91, 67, 83, 55, 91
(a) Complete the trace table for the key variables as the algorithm runs. Show only the iterations where MaxScore changes. [3]
| Index | Scores[Index] | MaxScore | MaxPos |
|---|---|---|---|
| Start | |||
(b) State the output of the program. [2]
(c) There are two elements with value 91 (at positions 4 and 8). Explain which position is reported and why. [1]
(a) Tracing the maximum-finding algorithm with Scores = [45, 72, 38, 91, 67, 83, 55, 91]: [3]
The algorithm initialises MaxScore to Scores[1] = 45 and MaxPos to 1, then loops from Index 2 to 8, updating whenever a larger value is found.
| Index | Scores[Index] | MaxScore | MaxPos |
|---|---|---|---|
| Start | - | 45 | 1 |
| 2 | 72 | 72 | 2 |
| 4 | 91 | 91 | 4 |
[1] for correct starting values (45, 1), [1] for the update at Index 2 (72 > 45), [1] for the update at Index 4 (91 > 72).
At Index 3, Scores[3] = 38, which is not greater than 72, so no change. At Index 5 (67), 6 (83), 7 (55), and 8 (91), none exceed the current MaxScore of 91. The value at Index 8 equals 91 but does not exceed it, so no update occurs.
(b) The output of the program: [2]
Highest score: 91 at position 4[1] for the value 91, [1] for position 4.
(c) Position 4 is reported (not position 8) because the comparison uses > (strictly greater than), not >= (greater than or equal to). [1]
When the algorithm reaches position 8 with value 91, it compares: is 91 > 91? The answer is no, because 91 equals 91 but is not strictly greater. Therefore MaxScore and MaxPos are not updated, and the first occurrence at position 4 is kept. If the condition were >=, the algorithm would update on ties and report position 8 instead.
Everything you need to excel in your exams