Try it on paper first. A hint, the key idea and the worked solution are here when you need them.
A car park charges by the whole hour. This pseudocode works out the charge in dollars.
DECLARE Hours : INTEGER
DECLARE Charge : INTEGER
INPUT Hours
IF Hours <= 1
THEN
Charge ← 0
ELSE
IF Hours <= 4
THEN
Charge ← 2 * Hours
ELSE
Charge ← 8 + 3 * (Hours - 4)
ENDIF
ENDIF
OUTPUT ChargeDry-run the program for the inputs 1, 3 and 6. What is the output each time?
IF <condition> then THEN, an optional ELSE, and ENDIF; THEN and ELSE are two spaces in. CASE OF <identifier> lists single values, each with one statement, tested in order; OTHERWISE comes last; ENDCASE closes it. Relational operators: =, <, <=, >, >=, <>. Logical: AND, OR, NOT.
Have you tried it?
Work it out on paper first. It is fine to get stuck or make a mistake: that is how we learn. When you are ready, go through the solution one step at a time, and check each step against your own.
Input 1. 1 <= 1 is TRUE, so Charge ← 0. The output is 0.
Input 3. 3 <= 1 is FALSE, so we go to the ELSE. There 3 <= 4 is TRUE, so Charge ← 2 * 3 = 6. The output is 6.
Input 6. Both tests are FALSE, so Charge ← 8 + 3 * (6 - 4) = 8 + 6 = 14. The output is 14.
Check. At 4 hours the middle rule gives , and the last rule starts at . The charge never jumps down, which is what a car park wants.
Answer: 0, 6 and 14 dollars.
Log in to join the discussion.
Loading…