Question 1 Report
A program needs to repeatedly accept temperature readings until a valid reading is entered. A valid temperature is between -50 and 60 degrees Celsius.
(a) Write pseudocode using a WHILE loop to keep asking for input until a valid temperature is entered. Output an error message for invalid input. [4]
(b) Rewrite your solution using a REPEAT...UNTIL loop. [2]
(c) Explain one difference between the WHILE loop and REPEAT...UNTIL loop versions. [2]
(a) The WHILE loop version uses a flag variable to control repetition. The flag is initially FALSE, and the loop body prompts for input, validates it, and sets the flag to TRUE when the temperature is in range: [4]
DECLARE Temperature : REAL
DECLARE Valid : BOOLEAN
Valid ← FALSE
WHILE Valid = FALSE DO
OUTPUT "Enter temperature (-50 to 60): "
INPUT Temperature
IF Temperature >= -50 AND Temperature <= 60 THEN
Valid ← TRUE
ELSE
OUTPUT "Invalid temperature. Try again."
ENDIF
ENDWHILE
OUTPUT "Temperature recorded: ", Temperature[1 mark for WHILE loop with correct condition, 1 mark for input inside loop, 1 mark for validation check, 1 mark for error message and flag update]
(b) The REPEAT...UNTIL version tests the condition after the body, guaranteeing the prompt runs at least once: [2]
REPEAT
OUTPUT "Enter temperature (-50 to 60): "
INPUT Temperature
IF Temperature < -50 OR Temperature > 60 THEN
OUTPUT "Invalid temperature. Try again."
ENDIF
UNTIL Temperature >= -50 AND Temperature <= 60
OUTPUT "Temperature recorded: ", Temperature[1 mark for REPEAT...UNTIL structure, 1 mark for correct exit condition]
(c) The WHILE loop tests its condition before the loop body executes, so if the condition is already FALSE at the start, the body never runs at all. [1] The REPEAT...UNTIL loop always executes the body at least once before testing the condition. For input validation this is more natural because the user must enter a value before it can be checked. [1]
Everything you need to excel in your exams