Again and again
Answers are for parents and teachers.
1
How many times does each loop run? (a) FOR a ← 1 TO 5 (b) FOR b ← 0 TO 5 (c) FOR c ← 4 TO 9
(a) 5 times. (b) 6 times: 0, 1, 2, 3, 4, 5. (c) 6 times: 4, 5, 6, 7, 8, 9.
2
Follow the algorithm. What is output?
Pseudocode
1OUTPUT "Ready" 2FOR t ← 3 TO 5 3 OUTPUT t - 1 4NEXT t 5OUTPUT "Go"
Ready, then the counter t is 3, 4 and 5, so the body outputs 2, 3 and 4. Then Go. Output: Ready, 2, 3, 4, Go, each on its own line.
3
Write a FOR loop that outputs the numbers 20 to 25.
FOR n ← 20 TO 25 / OUTPUT n / NEXT n. It runs 6 times.
4
The loop should output 1, 2, 3 and 4, and then Done once. The line NEXT k is missing. Explain why this is a problem and rewrite the algorithm correctly.
Pseudocode
1FOR k ← 1 TO 4 2 OUTPUT k 3OUTPUT "Done"
Without NEXT k there is no sign of where the loop ends, so a reader cannot tell if OUTPUT "Done" is inside the loop (and would be repeated) or after it. Correct: FOR k ← 1 TO 4 / OUTPUT k / NEXT k / OUTPUT "Done".
5
Give one everyday example of a count-controlled loop and one of a condition-controlled loop. Why must every loop have a way to stop?
For example: ‘Do 15 sit-ups’ is count-controlled; ‘Keep reading until the end of the chapter’ is condition-controlled. A loop with no way to stop never ends: it is an infinite loop, so the program never finishes until someone stops it or it crashes.