Selection and iteration: IF, CASE, FOR, WHILE and REPEAT
Programs are built from three structures: sequence (one step after another), selection (choosing a path) and iteration (repeating). Knowing which loop fits a problem is worth marks on its own.
Selection: IF and CASE
IF chooses between paths using a condition, with an optional ELSE. CASE chooses between several paths using the value of one variable, with OTHERWISE for any value not listed. CASE is neater when one variable is compared against many values.
CASE OF Zone
1 : Fare <- 150
2 : Fare <- 220
3 : Fare <- 300
OTHERWISE OUTPUT "Unknown zone"
ENDCASEThe three loops
- FOR … NEXT (count-controlled): repeats a known number of times, such as once for each of 30 students.
- WHILE … ENDWHILE (pre-condition): checks the condition first, so it may run no times at all. It suits “keep going while something is true”.
- REPEAT … UNTIL (post-condition): checks at the end, so it always runs at least once. It suits input that must be asked for at least once, such as a validation loop.
Nesting
A structure can go inside another: an IF inside a loop, or a loop inside a loop. With nested FOR loops, the inner loop runs all the way through for every pass of the outer one, so 3 outer passes × 4 inner passes is 12 runs of the inner body.
Where marks go
- Using a FOR loop when the number of repeats isn’t known in advance.
- Writing a WHILE loop whose condition never becomes false.
- Getting REPEAT … UNTIL backwards: it stops when the condition becomes true.
- Missing ENDIF, ENDWHILE, NEXT or ENDCASE.
- Using a chain of IFs where the conditions overlap, so more than one branch runs.
Try a question
3 MARKS · MARKED ON THIS PAGEA music app describes how fast a song is from its tempo in beats per minute. Write pseudocode that: - inputs a whole number into the variable Tempo - outputs the message Slow if Tempo is less than 60 - outputs the message Moderate if Tempo is from 60 to 120 inclusive - outputs the message Fast if Tempo is greater than 120. Output only one of the three messages, exactly as written, and nothing else.
solutionPseudocode
Loading...
Type your answer first.