Lesson 3 of 8
Algorithms: Lesson 3

Sequence, Selection and Iteration

Every algorithm ever written - from a sorting function to a search engine - is built from exactly three programming constructs. Master these and you can read, write and trace any algorithm.

50 minutes Interactive code tracer included
Pseudocode style: Saved automatically

In 1966, two computer scientists - Bohm and Jacopini - proved something remarkable: any computable problem can be solved using just three control structures. You do not need dozens of special keywords or obscure constructs. Just three. Sequence. Selection. Iteration. Every program you have ever run is ultimately an arrangement of these three patterns, no matter how complex it appears on the surface.

Think about it: Consider a vending machine. It executes steps in order (sequence: accept money, then check selection). It makes decisions (selection: if the item is in stock, dispense it; otherwise, refund). It repeats actions (iteration: keep checking coins until the total is sufficient). Name which construct is which in this scenario before you read on.
Terms you need to know
Sequence
Statements that execute one after another in the order they are written. The default mode of execution.
Selection
A construct that chooses between two or more paths based on a condition. Implemented using IF/ELSE or CASE/SWITCH.
Iteration
Repeating a block of code. Count-controlled (FOR) or condition-controlled (WHILE / DO...WHILE).
Condition
A Boolean expression that evaluates to True or False. Controls which branch of a selection is taken and when iteration stops.
FOR loop
A count-controlled loop that executes a set number of times, determined before the loop starts.
WHILE loop
A condition-controlled loop that continues as long as a condition is true. The number of iterations is not fixed in advance.
Sequence

Sequence is the simplest construct: statements execute one after another, in the exact order they appear. There is no branching, no repetition - just a straight-line execution from top to bottom. It is the default behaviour of any algorithm unless selection or iteration keywords appear.

Even the most complex programs ultimately reduce to sequences of instructions at the hardware level. Everything else is just a way of controlling which sequences run in which order.

// A simple sequential calculation (AQA)
OUTPUT "Enter length: "
length ← USERINPUT
OUTPUT "Enter width: "
width ← USERINPUT
area  length * width
perimeter  2 * (length + width)
OUTPUT "Area: " + area
OUTPUT "Perimeter: " + perimeter
# A simple sequential calculation (OCR)
print("Enter length: ")
length = input()
print("Enter width: ")
width = input()
area = length * width
perimeter = 2 * (length + width)
print("Area: " + area)
print("Perimeter: " + perimeter)
Order matters in sequence

If you swap two lines of a sequential algorithm, the result often changes - or the algorithm breaks entirely. You cannot calculate area = length * width before you have assigned values to length and width. This seems obvious, but in an exam trace question, order errors are a common mistake to watch for.

Selection

Selection allows an algorithm to choose between different paths based on whether a condition is true or false. Without selection, every user would get the same output regardless of their input, which makes most real programs impossible.

Selection is implemented with IF/ELSE or CASE (switch) statements. The condition is always a Boolean expression - one that evaluates to either True or False.

Basic IF/ELSE:

score ← USERINPUT
IF score >= 50 THEN
    OUTPUT "Pass"
ELSE
    OUTPUT "Fail"
ENDIF
score = input()
if score >= 50 then
    print("Pass")
else
    print("Fail")
end if

Nested IF (ELSEIF) for multiple grades:

score ← USERINPUT
IF score >= 90 THEN
    OUTPUT "Grade A"
ELSEIF score >= 70 THEN
    OUTPUT "Grade B"
ELSEIF score >= 50 THEN
    OUTPUT "Grade C"
ELSE
    OUTPUT "Fail"
ENDIF
score = input()
if score >= 90 then
    print("Grade A")
elseif score >= 70 then
    print("Grade B")
elseif score >= 50 then
    print("Grade C")
else
    print("Fail")
end if
Exam angle

Common error: students write conditions in the wrong order for graded thresholds. If you check score >= 50 before score >= 90, a score of 95 would match the first condition and be graded C, never reaching the A check. Always check conditions from the most restrictive (highest threshold) to the least restrictive.

Iteration

Iteration repeats a block of code. This is essential for processing lists, validating input, searching, sorting - almost every non-trivial algorithm needs at least one loop. There are two types: count-controlled (FOR) and condition-controlled (WHILE).

Count-controlled: FOR loop

Use a FOR loop when you know exactly how many times the loop should run before it starts. The loop counter is set to a start value, compared to an end value, and incremented automatically each iteration.

// Print 5 to 1 countdown (AQA)
FOR i  5 TO 1 STEP -1
    OUTPUT i
ENDFOR
OUTPUT "Blast off!"
# Print 5 to 1 countdown (OCR)
for i = 5 to 1 step -1
    print(i)
next i
print("Blast off!")
Condition-controlled: WHILE loop

Use a WHILE loop when you do not know in advance how many iterations are needed - the loop continues until a condition becomes false. The condition is checked before the loop body executes, so if the condition is already false, the loop body never runs.

// Find the first power of 2 greater than 1000 (AQA)
n  1
WHILE n <= 1000
    n  n * 2
ENDWHILE
OUTPUT n    // outputs 1024
# Find the first power of 2 greater than 1000 (OCR)
n = 1
while n <= 1000
    n = n * 2
end while
print(n)    # outputs 1024
Choosing the right loop type

Use FOR when you know the number of iterations: "process all 10 items", "run 5 times", "check all 26 letters".

Use WHILE when you do not know: "keep asking until valid input", "repeat until the list is sorted", "continue until we find the target".

A common exam question asks you to justify which loop type you chose. Always give a reason tied to whether the number of iterations is known in advance.

Exam angle

Watch for the "off-by-one" error in FOR loops. FOR i ← 1 TO 10 runs 10 times (i=1,2,...,10). FOR i ← 0 TO 10 runs 11 times. In exam questions, always count carefully: "how many times does this loop execute?" is frequently tested. Also know that a WHILE loop may run zero times if its condition is false from the start - unlike a DO...WHILE loop which always runs at least once.

A complete worked example

Real algorithms combine all three constructs. This example counts how many numbers entered by the user are above average. It uses sequence (to store running totals), iteration (to process each input), and selection (to compare each value to the average).

// Count how many of 5 numbers are above the average (AQA)
total  0
FOR i  1 TO 5            // ITERATION: repeat 5 times
    OUTPUT "Enter number " + i
    num ← USERINPUT
    total  total + num    // SEQUENCE: update running total
ENDFOR
average  total / 5
OUTPUT "Average: " + average
aboveCount  0
FOR i  1 TO 5            // Second pass to count above-average values
    OUTPUT "Enter number " + i
    num ← USERINPUT
    IF num > average THEN    // SELECTION: compare to average
        aboveCount  aboveCount + 1
    ENDIF
ENDFOR
OUTPUT aboveCount + " numbers above average"
# Count how many of 5 numbers are above the average (OCR)
total = 0
for i = 1 to 5
    print("Enter number " + i)
    num = input()
    total = total + num
next i
average = total / 5
print("Average: " + average)
aboveCount = 0
for i = 1 to 5
    print("Enter number " + i)
    num = input()
    if num > average then
        aboveCount = aboveCount + 1
    end if
next i
print(aboveCount + " numbers above average")
Step through an algorithm

Press Step to execute one line at a time and watch the variables update. Press Reset to start over.

Variable state
count = 0
total = 0
i = -
Output

Test yourself

1. Which construct describes statements that execute one after another in the order they are written?

Sequence is the default mode of execution - statements run in the order they appear, with no branching or repetition. It is the most fundamental construct.

2. When should a FOR loop be preferred over a WHILE loop?

A FOR loop is used when you know exactly how many iterations are needed before the loop starts. If the number is determined at runtime (e.g. "keep asking until valid input"), use a WHILE loop instead.

3. How many times does this loop execute? FOR i ← 1 TO 10 STEP 2

With STEP 2, the counter takes values 1, 3, 5, 7, 9 - that is 5 values. The loop runs 5 times. The next value would be 11, which exceeds 10, so the loop exits after i=9.

4. The following condition tests a grade: IF score >= 50 THEN output "C" ELSEIF score >= 70 THEN output "B". A student scores 85. What is output?

The conditions are checked in order. 85 >= 50 is True, so "C" is output and the algorithm exits the IF block immediately without ever checking the second condition. This is the classic threshold ordering error - the >= 70 check for B is never reached for a score of 85. The fix: always check from the highest threshold first.

5. A WHILE loop begins: WHILE x > 0. Before the loop starts, x = -3. How many times does the loop body execute?

A WHILE loop checks its condition before the body runs. Since -3 > 0 is False before the first iteration, the loop body never executes at all. This is a key difference from a DO...WHILE loop, which always runs the body at least once.
Challenge question

A student writes a program to calculate the factorial of a number n (n! = 1 x 2 x 3 x ... x n). They use the algorithm below. Trace it for n = 5 and state the output. Then explain one way the algorithm could fail and what input value would cause it.

n ← USERINPUT
result  1
FOR i  1 TO n
    result  result * i
ENDFOR
OUTPUT result
Trace for n = 5:
result starts at 1.
i=1: result = 1*1 = 1
i=2: result = 1*2 = 2
i=3: result = 2*3 = 6
i=4: result = 6*4 = 24
i=5: result = 24*5 = 120
Output: 120. Correct - 5! = 120.

Failure case: If n = 0, the FOR loop runs from 1 TO 0. Since 1 > 0, the loop body never executes and result remains 1. The output would be 1, which is actually mathematically correct (0! = 1 by convention), but if n is negative (e.g. -3), the loop still never runs and outputs 1 - but factorial is undefined for negative numbers, so the output is meaningless. The algorithm needs input validation to reject negative values.
Printable Worksheets

Practice what you have learned

Three levelled worksheets. Download, print and complete offline.

Recall
Sequence, Selection and Iteration
Label each construct in code snippets, fill-in keywords, and identify loop types from descriptions.
Download
Apply
Writing and Tracing Algorithms
Write pseudocode for four given problems using appropriate constructs. Trace two algorithms step by step.
Download
Exam Style
Exam-Style Questions
Complete a trace table, identify the error in a selection construct, and write an algorithm combining all three constructs.
Download
Lesson 3 - Algorithms
Sequence, Selection and Iteration
Starter activity
Show students a vending machine video or image. Ask: "Can you find an example of sequence, selection and iteration in how a vending machine works?" Give 3 minutes to write down one example of each. Share answers - this grounds the abstract constructs in a familiar real-world system before any pseudocode is introduced.
Lesson objectives
1
Define sequence, selection and iteration and explain the role of each in algorithm design.
2
Write correct pseudocode using IF/ELSEIF/ELSE for single and multi-branch selection.
3
Write correct pseudocode for count-controlled (FOR) and condition-controlled (WHILE) loops.
4
Identify which loop type is more appropriate for a given scenario and justify the choice.
5
Trace an algorithm that combines all three constructs and produce the correct output.
Key vocabulary
Sequence
Statements executing in written order. No branching or repetition. The default mode.
Selection
IF/ELSE or CASE. Chooses one path from two or more based on a Boolean condition.
Count-controlled iteration
FOR loop. Number of iterations known before the loop starts.
Condition-controlled iteration
WHILE loop. Continues until a condition becomes false. May run zero times.
Discussion questions
Can you think of a useful program that uses only sequence, with no selection or iteration at all?
What happens if the condition in a WHILE loop never becomes false? What is this called?
Why does checking conditions in the wrong order in a multi-branch IF cause errors?
Exit tickets
Give one reason why a FOR loop is more appropriate than a WHILE loop for processing all items in a 10-item list. [1 mark]
How many times does FOR i ← 0 TO 9 execute? [1 mark]
Write pseudocode that outputs "even" or "odd" depending on whether a user-entered number is divisible by 2. [3 marks]
Homework suggestion
Write an algorithm for a number guessing game. The computer picks a secret number between 1 and 100. The user guesses repeatedly. After each guess, the algorithm outputs "too high", "too low" or "correct". The algorithm tracks how many guesses were needed. Identify which construct is used for each part of the algorithm.