Loops in new clothes
Answers are for parents and teachers.
1
Write FOR box ← 1 TO 3 / OUTPUT box / NEXT box in two other formats: one with END FOR and one with IN RANGE.
END FOR: FOR box = 1 TO 3 / OUTPUT box / END FOR. RANGE: FOR box IN RANGE(1, 4) / OUTPUT box. All three output 1, 2 and 3.
2
What numbers does the counter take in FOR n IN RANGE(6, 10)? How many times does the loop run?
6, 7, 8 and 9. The stop value 10 is not used. It runs 4 times.
3
Follow the flowchart when the user types 4, and again when the user types 1. What is output each time?
4: k is 2, 3 and 4, so the output is 2, 3, 4. 1: k is 2 and 2 <= 1 is No, so nothing is output.
4
Draw a flowchart for this loop. Write down its output.
Pseudocode
1FOR plant ← 1 TO 3 2 OUTPUT "Water plant ", plant 3NEXT plant
Start; plant ← 1; diamond plant <= 3? Yes: OUTPUT "Water plant ", plant; plant ← plant + 1; back to the diamond; No: end. Output: Water plant 1, Water plant 2, Water plant 3.
5
The user types a limit. What happens in FOR n ← 1 TO limit when the limit is 0? Why is that a sensible way for a loop to behave?
The first test fails at once, so the body runs zero times and the program carries on after NEXT n. This is sensible because ‘0 things to do’ means do nothing.