Question 1
2 marksThis algorithm should output all the even numbers from 2 to 20, but it does not.
01// output the even numbers from 2 to 20
02for n = 2 to 18 step 2
03 print(n)
04next nIdentify the line that contains the error, and write the corrected line.
Model answer
Line 2 is wrong: the loop ends at 18, so 20 is never output.
Corrected line:
for n = 2 to 20 step 2
Explanation
An ERL for loop includes its end value, and step 2 makes n go up in twos. With an end value of 18, the outputs are 2, 4, ..., 18, so 20 is missing. Changing the end value to 20 gives all ten even numbers. In Python the end value of range is not included, so the equivalent is range(2, 21, 2).
Mark scheme
-
1 mark
Line 2 (the loop stops at 18, so 20 is not output)
-
1 mark
for n = 2 to 20 step 2
Accept for n = 2 to 21 step 2 (it also stops after 20). Accept an equivalent in a high-level language, e.g. for n in range(2, 21, 2) or range(2, 22, 2). Do not accept range(2, 20, 2) (stops at 18).