For Loop CS Thinking Example 4
Follow the full solution, then compare it with the other examples linked below.
Example 4
mediumWhat does this code output?
SET scores = [85, 92, 78, 95, 88]
SET highest = scores[0]
FOR i = 1 TO LENGTH(scores) - 1
IF scores[i] > highest THEN
SET highest = scores[i]
END IF
END FOR
OUTPUT highest
Solution
- 1 Step 1: highest = scores[0] = 85.
- 2 Step 2: i=1 โ scores[1]=92 > 85? YES โ highest = 92.
- 3 Step 3: i=2 โ scores[2]=78 > 92? NO โ highest stays 92.
- 4 Step 4: i=3 โ scores[3]=95 > 92? YES โ highest = 95.
- 5 Step 5: i=4 โ scores[4]=88 > 95? NO โ highest stays 95.
Answer
95. The FOR loop implements the 'find maximum' pattern: initialise with the first element, then compare each remaining element.
The find-maximum pattern is one of the most common FOR loop algorithms. Starting from index 1 (not 0) avoids a redundant comparison with the element already stored in highest.
About For Loop
A control structure that repeats a block of code a specific number of times or once for each item in a collection. The loop variable is automatically set to each successive value in the range or collection, eliminating the need to manually update it.
Learn more about For Loop โ