Sub topic 3
Expressing Sequence, Selection, and Iteration
Every algorithm you will write in this tutorial is built from three control structures. Sequence runs steps one after another. Selection chooses between steps based on a condition. Iteration repeats steps. This chapter shows how to write each one in pseudocode so that a reader cannot misread it, and it covers the mistakes that most often slip in.
This chapter assumes you can already write conditionals and loops in at least one programming language. It also uses the conventions from the previous chapter: ← for assignment, uppercase keywords, indentation to show nesting, and explicit END markers such as END IF and END WHILE.
Sequence: Order Is Meaning
A sequence is a list of statements that run top to bottom, each one once. It is the simplest structure, and order errors in it are still common. Swapping two variables is the standard example:
temp ← a
a ← b
b ← tempIf you reorder these lines to a ← b, b ← a, both variables end up holding the original value of b. When you write a sequence, ask what each line needs from the lines before it. If a line reads a variable, some earlier line must have set that variable to the value you intend.
Selection: Choosing a Path
Selection runs a block only when a condition is true. Pseudocode has three common forms.
IF, IF–ELSE, and ELSE IF chains
IF temperature > 30 THEN
OUTPUT "hot"
END IF
IF n MOD 2 = 0 THEN
parity ← "even"
ELSE
parity ← "odd"
END IF
IF score ≥ 90 THEN
grade ← "A"
ELSE IF score ≥ 80 THEN
grade ← "B"
ELSE IF score ≥ 70 THEN
grade ← "C"
ELSE
grade ← "F"
END IFIn an ELSE IF chain, the conditions are tested in order and only the first true branch runs. That is why score ≥ 80 does not need to say AND score < 90: any score of 90 or more was already caught. The order is part of the logic. If you put score ≥ 70 first, every passing student gets a C.
CASE for many discrete values
When you branch on one variable that takes a few exact values, a CASE statement reads more clearly than a long chain:
CASE day OF
"Sat", "Sun": rate ← 1.5
"Fri": rate ← 1.2
OTHERWISE: rate ← 1.0
END CASEAlways include OTHERWISE (or a final ELSE) unless you can show that no other value is possible. A missing default leaves rate unset for unexpected input, and that becomes a bug once the code runs.
Common selection errors
- Gaps and overlaps. Conditions such as
x < 0andx > 0leave outx = 0. Check the boundary values of every comparison. - Unclosed blocks. Without
END IF, a reader cannot tell whichIFanELSEbelongs to (the "dangling else" problem). End markers settle it. - Using
=for both test and assignment. Keep←for assignment and=for comparison.
Iteration: Repeating Steps
Pseudocode usually offers three loops. They differ in when the condition is checked and in who controls the count.
FOR: a counted loop
FOR i ← 1 TO n DO
OUTPUT i
END FORPseudocode FOR bounds are inclusive. This loop runs for i = 1, 2, …, n, so the body runs n times. If n is less than 1, the body runs zero times. You can count down or skip with STEP:
FOR i ← n DOWNTO 1 DO
OUTPUT i
END FOR
FOR i ← 0 TO 10 STEP 2 DO
OUTPUT i
END FORDo not assign to the loop variable inside a FOR body. Readers expect a FOR to run a fixed number of times. If the count needs to change while the loop runs, use WHILE.
WHILE: a pre-test loop
WHILE balance < target DO
balance ← balance × 1.05
years ← years + 1
END WHILEThe condition is checked before each pass. If it is false at the start, the body never runs. The body must change something the condition depends on. Otherwise the loop never ends.
REPEAT–UNTIL: a post-test loop
REPEAT
OUTPUT "Enter a value from 1 to 10"
INPUT x
UNTIL x ≥ 1 AND x ≤ 10The body runs at least once, and the condition is checked afterward. Note the polarity: UNTIL gives the condition for stopping, while WHILE gives the condition for continuing. Converting between them means negating the condition. The loop above is equivalent to "repeat while x < 1 OR x > 10".
Comparing the loops
| Loop | Condition checked | Minimum body runs | Typical use |
|---|---|---|---|
| `FOR i ← a TO b` | Implicitly, before each pass | 0 | Known number of passes, stepping through an array |
| `WHILE cond` | Before each pass | 0 | Repeat while something holds; count unknown |
| `REPEAT … UNTIL cond` | After each pass | 1 | Body must run once, e.g. input validation |
Common iteration errors
- Off-by-one bounds. Writing
< nwhen you mean≤ n, or starting at 0 instead of 1. You will trace these errors in detail in later chapters. - No progress. A
WHILEbody that never changes the tested variable. - Wrong polarity. Copying a
WHILEcondition into anUNTILwithout negating it. - Mixed loop styles. Using
FORbut then changingiinside the body, which makes the pass count impossible to read off the header.
Combining the Structures
Real algorithms nest these structures inside each other. The following counts the positive, negative, and zero entries of an array A of length n:
pos ← 0
neg ← 0
zero ← 0
FOR i ← 1 TO n DO
IF A[i] > 0 THEN
pos ← pos + 1
ELSE IF A[i] < 0 THEN
neg ← neg + 1
ELSE
zero ← zero + 1
END IF
END FORAll three structures appear here. Sequence sets up the counters. Iteration visits each element. Selection sorts each element into exactly one category. The final ELSE makes the branches cover every possible value with no gaps, so pos + neg + zero = n always holds when the loop ends. A quick check like that sum is a good habit to build.
Checking the Semantics in Real Code
Languages map these structures in different ways, so it is worth checking the pseudocode meanings against one. Python's range excludes its upper bound, and Python has no post-test loop. The program below reproduces the inclusive FOR, a WHILE, and a REPEAT–UNTIL:
n = 4
# FOR i <- 1 TO n (inclusive upper bound)
for i in range(1, n + 1):
print("for", i)
# WHILE balance < target
balance, target, years = 100.0, 120.0, 0
while balance < target:
balance *= 1.05
years += 1
print("years:", years)
# REPEAT ... UNTIL x >= 1 AND x <= 10
values = iter([0, 15, 7]) # stands in for user input
while True:
x = next(values)
print("got", x)
if 1 <= x <= 10:
breakRunning it prints for 1 through for 4, then years: 4, then got 0, got 15, and got 7. The while True … break pattern runs the body before testing, which is how a post-test loop is written in Python. Translating pseudocode into code is covered fully in the final chapter. For now, notice that TO n became n + 1 in Python.
Exercise
Rewrite this loop as a REPEAT–UNTIL loop that behaves identically for all n ≥ 1, and say what changes when n = 0. WHILE i ≤ n DO OUTPUT i i ← i + 1 END WHILE (Assume i ← 1 just before the loop.)
Show answer
REPEAT / OUTPUT i / i ← i + 1 / UNTIL i > n. The stop condition is the negation of i ≤ n. For n ≥ 1 both loops print 1 to n. For n = 0 the WHILE loop prints nothing, but the REPEAT loop prints 1 once, because a post-test loop always runs its body at least once. To match exactly, wrap the REPEAT in IF n ≥ 1 THEN … END IF.
Exercise
A student writes the following to classify a BMI value b. Find the logic error and fix it. IF b ≥ 18.5 THEN category ← "normal" ELSE IF b ≥ 25 THEN category ← "overweight" ELSE category ← "underweight" END IF
Show answer
The conditions are in the wrong order. Any b ≥ 25 already satisfies b ≥ 18.5, so the "overweight" branch can never run. Test the higher threshold first: IF b ≥ 25 THEN "overweight", ELSE IF b ≥ 18.5 THEN "normal", ELSE "underweight".
Exercise
How many times does the body of FOR k ← 3 TO 10 STEP 3 run, and which values does k take? How many times does FOR k ← 5 TO 2 run?
Show answer
The first loop runs 3 times, with k = 3, 6, 9 (12 exceeds 10). The second loop runs 0 times, because the start value already exceeds the end value and there is no DOWNTO.