Selection and iteration
| English | Chinese | Pinyin |
|---|---|---|
| selection | 选择 | xuǎn zé |
| iteration | 迭代 | dié dài |
| count-controlled | 计数控制 | jì shù kòng zhì |
| pre-condition | 前置条件 | qián zhì tiáo jiàn |
| post-condition | 后置条件 | hòu zhì tiáo jiàn |
Choosing and repeating
- 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 runs the branch that matches the value
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.

FOR counts a known number of times; WHILE tests before (may run zero times); REPEAT tests after (runs at least once)
Trace a loop, pass by pass
A trace table records each variable after every pass of the loop. Watch the counter i climb while the running total builds up — exactly what an exam trace question asks you to fill in.
Match each loop to when you'd use it.
FOR = count-controlled; WHILE = condition tested before (0+ passes); REPEAT = condition tested after (1+ passes).
After total = 0; FOR i = 1 TO 5: total = total + i, what is the value of total?
Adding 1+2+3+4+5 = 15 — exactly what the trace table builds up pass by pass.
REPEAT...UNTIL tests its condition AFTER the body, so the body always runs at least once.
That post-condition test is the difference from WHILE, which can run zero times.
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.
- Each construct is written in pseudocode before coding.
"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?