Selection and iteration
Selection and iteration
- Programs make choices (selection) and repeat work (iteration).
- These are two of the three core constructs.
- Choosing the right loop is a common exam question.
Selection
IF age >= 18 THEN
OUTPUT "Adult"
ELSE
OUTPUT "Minor"
ENDIF
- For many cases, deep nested IFs are hard to read — a CASE is cleaner when testing one value against several options:
CASE OF Grade
"A": OUTPUT "Excellent"
"B": OUTPUT "Good"
OTHERWISE: OUTPUT "Try again"
ENDCASE
A CASE statement is cleaner than nested IFs when you are:
CASE matches one value against many possibilities; deep nested IFs become hard to read.
The three loops
- FOR (count-controlled) — when you know how many times:
FOR i ← 1 TO 10 … NEXT i. - WHILE (pre-condition) — tests before each pass, so it may run zero times.
- REPEAT...UNTIL (post-condition) — tests after each pass, so it always runs at least once.
A FOR (count-controlled) loop is best when:
FOR is for a known, fixed number of repeats (or processing each array element).
A WHILE loop tests its condition before each pass, which means it:
WHILE checks first, so if the condition is false at the start the body never runs.
Which loop always runs its body at least once?
REPEAT...UNTIL tests the condition after the body, so the body runs at least once.
Choosing the right loop
- Count known up front → FOR.
- May need zero passes → WHILE.
- Must run at least once → REPEAT...UNTIL.
- e.g. "ask for a password until it's correct, but always ask at least once" → REPEAT...UNTIL.
"Keep asking for a password until it is correct, but always ask at least once." Which loop fits?
You must ask at least once, so the post-condition REPEAT...UNTIL is the natural choice.
You've got it
- IF/ELSE for a choice; CASE when testing one value against many options
- FOR = count known; WHILE = may run 0 times; REPEAT = runs at least once
- pick the loop by: is the count known? must the body run at least once?