Selection and Iteration
Selection and iteration
Two of the three programming constructs let a program make decisions (selection) and repeat work (iteration). Together they give programs their logic and power.
Selection
Selection chooses which code to run based on a condition (something that is True or False).
IF / ELSE IF / ELSE
if age < 13 then
output "Child"
elseif age < 18 then
output "Teenager"
else
output "Adult"
endif
- The conditions are checked in order; the first true one runs and the rest are skipped.
ELSEcatches everything not already matched.
Nested selection
An IF inside another IF — used when a decision depends on more than one thing.
Comparison & logical operators in conditions
Use ==, !=, <, >, <=, >= and combine with AND, OR, NOT:
if age >= 13 AND age < 18 then ...
Iteration (loops)
Iteration repeats a block of code. There are two families: count-controlled and condition-controlled.
Count-controlled: FOR
Repeats a set number of times — use when you know how many repeats are needed.
for i = 1 to 5
output i
next i
This prints 1 2 3 4 5.
Condition-controlled: WHILE
Repeats while a condition is True — the condition is checked before each pass, so the loop may run zero times.
while password != "letmein"
input password
endwhile
Condition-controlled: DO … UNTIL / REPEAT
Repeats until a condition becomes True — the condition is checked after each pass, so the loop always runs at least once.
repeat
input number
until number > 0
FOR vs WHILE — which to use?
- Use FOR when the number of repeats is known (e.g. process 10 items).
- Use WHILE when repeats depend on a condition that may change (e.g. keep asking until valid input). A WHILE can run 0 times; a REPEAT/UNTIL runs at least once.
Worked example
How many times does this run? for i = 2 to 8 — outputs each i.
- From 2 to 8 inclusive = 2,3,4,5,6,7,8 → 7 times. ✓
Common mistakes
- Infinite loops — a WHILE whose condition never becomes False (forgetting to change the variable inside).
- Off-by-one errors — forgetting FOR loops are usually inclusive of the end value.
- Using a WHILE when you know the exact count (a FOR is clearer), or vice versa.
Exam tips
- Be able to trace a loop with a trace table, writing the variable values each pass.
- State clearly: FOR = known number of repeats; WHILE = check condition first (may run 0 times); REPEAT/UNTIL = check after (runs ≥ 1 time).
- Watch the loop's start and end values for off-by-one slips.
Key facts to remember
- Selection = IF / ELSE IF / ELSE, using conditions and AND/OR/NOT.
- Count-controlled (FOR) = set number of repeats; condition-controlled (WHILE/REPEAT) = repeat based on a condition.
- WHILE checks before (0+ runs); REPEAT…UNTIL checks after (1+ runs).