Repeat and reuse
Answers are for parents and teachers.
1
Write three loops. (a) Output Hello 8 times with the counter starting at 1. (b) Do the same with the counter starting at 0. (c) Output the numbers 10 to 15.
(a) FOR k ← 1 TO 8 / OUTPUT "Hello" / NEXT k. (b) FOR k ← 0 TO 7 / OUTPUT "Hello" / NEXT k. (c) FOR n ← 10 TO 15 / OUTPUT n / NEXT n.
2
Trace the algorithm for n = 5, and then for n = 0. Give the output each time.
Pseudocode
1INPUT n 2total ← 0 3FOR i ← 1 TO n 4 total ← total + i 5NEXT i 6OUTPUT total
n = 5: total becomes 1, 3, 6, 10, 15, so the output is 15. n = 0: the loop FOR i ← 1 TO 0 does not run, so the output is 0.
3
Write pseudocode. The user types how many pets they have, then the weight of each pet in kg. Output the total weight and the average weight. Make it safe if the user has no pets.
INPUT n / total ← 0 / FOR p ← 1 TO n / INPUT weight / total ← total + weight / NEXT p / OUTPUT "Total: ", total / IF n > 0 THEN OUTPUT "Average: ", total / n ELSE OUTPUT "No pets" ENDIF. Test: 2 pets of 4 and 6 kg give total 10 and average 5.
4
Give two reasons why a programmer writes a sub-routine instead of copying the same lines again and again.
Any two of: the lines are written and tested only once; a change has to be made in only one place; the main program is shorter and easier to read; the sub-routine can be reused in other programs.
5
Write a sub-routine greet() that outputs Good morning. In the main part, call it three times with a loop, and then once more only if the user types yes. How many lines are output when the user types no?
SUB-ROUTINE greet() / OUTPUT "Good morning" / END SUB. Main: FOR k ← 1 TO 3 / greet() / NEXT k / INPUT answer / IF answer = "yes" THEN greet() ENDIF. When the user types no, 3 lines are output.