CS
Topic 8 Decisions & patterns · 8.6 · 8.7 · 8.8 · 8.9 · 8.10 · 8.11

Decisions & Patterns

Programs make decisions with selection and repeat work with iteration. Master the two selection constructs (IF and CASE), the three loop types (FOR, WHILE, REPEAT), the counter and totaller patterns, string manipulation, and how they combine when nested. This is where a script becomes a real program.

🧪 Exam Mode ON — recall from memory, then reveal

📚 Book Notes — start here

Read this before you tap the activities. These notes give you everything you need before the Control Flow Simulator. When you're ready, tap 🎓 Learn.

🎯 Topic Overview

You've learned that programs run in sequence — top to bottom. Now they need to decide and repeat. Selection chooses which lines to run based on data (IF for two-way, CASE for value-matching). Iteration runs lines repeatedly using one of three loops: FOR (count-controlled), WHILE (pre-condition), REPEAT (post-condition). Choosing the RIGHT loop for the task is the biggest single skill in this section. Add string handling and nesting and you can express any real-world logic in code.

🎓 Learning Objectives

By the end of Topic 8.6–8.11 you should be able to…

  • Write IF...THEN...ELSE...ENDIF for two-way decisions
  • Chain IF-ELSE-IF for multi-way decisions
  • Write CASE OF...OTHERWISE...ENDCASE for value-matching selection
  • Write FOR...NEXT loops for count-controlled iteration
  • Write WHILE...ENDWHILE loops for pre-condition iteration (may run 0 times)
  • Write REPEAT...UNTIL loops for post-condition iteration (runs ≥ 1 time)
  • Choose the right loop for the task — the biggest skill in this section
  • Use the counter pattern (starts at 0, increments) and totaller pattern (starts at 0, accumulates)
  • Use string functions: LENGTH, SUBSTRING, LCASE, UCASE
  • Read, write and trace nested statements (IF-in-IF, FOR-in-FOR)

📖 Key Terminology

TermOne-line definition
SelectionA control structure that chooses which code to run based on a condition.
IF statementTwo-way selection: IF cond THEN ... ELSE ... ENDIF.
CASE statementMulti-way selection based on the value of a single variable.
OTHERWISEThe default branch of a CASE — runs when no other case matches.
IterationA control structure that repeats code — also called looping.
FOR loopCount-controlled loop: runs a fixed number of times.
WHILE loopPre-condition loop: checks the condition BEFORE running the body. May run 0 times.
REPEAT loopPost-condition loop: runs the body FIRST, checks after. Always runs ≥ 1 time.
CounterVariable that counts occurrences. Starts at 0, adds 1 when condition met.
TotallerVariable that accumulates values (also called accumulator). Starts at 0, adds values.
Nested loopA loop inside another loop.
SUBSTRINGFunction that extracts a portion of a string: SUBSTRING(str, start, length).
LENGTHFunction that returns the count of characters in a string.
LCASE / UCASEFunctions that return a string in lower / upper case.

🧠 Core Theory

Selection: IF vs CASE — pick the right one

UseWhen to use itExample
IFTwo-way (or few branches) based on any condition — including >, <, ranges, combined logic.IF Score >= 50 THEN Pass ELSE Fail
CASEMultiple branches based on a SINGLE variable's value — cleaner than long IF chains.CASE Grade OF 'A': ... 'B': ... OTHERWISE ...

The three iteration constructs — pick the right loop

LoopWhen to use itRuns at least once?
FORYou know EXACTLY how many iterations — a fixed number.Yes (if range valid)
WHILEYou DON'T know how many — you check a condition first. Loop may run 0 times.❌ No — condition might be false immediately
REPEATYou DON'T know how many, but the body must run AT LEAST ONCE — condition checked after.✅ Yes — always at least once

Counter vs Totaller — the two accumulator patterns

PatternPurposeUpdate line
CounterCount how many items match a conditionCount <- Count + 1
TotallerSum values into a running totalTotal <- Total + Value

String functions

FunctionReturnsExample
LENGTH(s)INTEGER count of charactersLENGTH("hello") = 5
SUBSTRING(s, start, len)STRING extract, start is 1-basedSUBSTRING("HELLO", 2, 3) = "ELL"
LCASE(s)STRING in lower caseLCASE("Hello") = "hello"
UCASE(s)STRING in upper caseUCASE("Hello") = "HELLO"

💡 Worked Examples

Example 1 · WHILE loop with input validation

Keep asking for an age until the user enters a valid one (0–120):

DECLARE Age : INTEGER
INPUT Age
WHILE Age < 0 OR Age > 120
    OUTPUT "Invalid age. Try again."
    INPUT Age
ENDWHILE
OUTPUT "Age accepted: ", Age

WHILE is right here because the user MIGHT enter a valid age first time (loop runs 0 times). If we used REPEAT, we'd ask twice minimum.

Example 2 · Nested FOR loop generating a table

Print the first 3 rows of a multiplication table:

FOR i <- 1 TO 3
    FOR j <- 1 TO 5
        OUTPUT i * j, " "
    NEXT j
    OUTPUT NEWLINE
NEXT i

Outer FOR = rows. Inner FOR = columns. Each iteration of the outer loop makes the inner loop run its full range. Close inner NEXT before outer NEXT.

Example 3 · SUBSTRING extracting initials

Get the first character of a name as a single character:

DECLARE Name : STRING
DECLARE Initial : CHAR
INPUT Name
Initial <- SUBSTRING(Name, 1, 1)
OUTPUT "Initial: ", Initial

Cambridge SUBSTRING is 1-based (start=1 for the first character). Length=1 gives you exactly one character.

⚠️ Common Misconceptions

❌ Using FOR when the iteration count isn't known

FOR is for a FIXED number of iterations. If you're waiting for user input to satisfy a condition, you need WHILE or REPEAT. Cambridge examiners have flagged "attempted to rewrite the algorithm with another FOR loop" as a recurring error.

❌ Missing OTHERWISE in CASE

Cambridge CASE statements need an OTHERWISE (the default). Without it, an unmatched value has no defined behaviour. It's not optional in Cambridge pseudocode.

❌ Confusing WHILE and REPEAT

WHILE checks BEFORE (may run 0 times). REPEAT checks AFTER (always ≥ 1 time). Ask yourself: "Should the body run even if the condition is false initially?" If yes → REPEAT. If no → WHILE.

❌ SUBSTRING off-by-one on start position

Cambridge SUBSTRING is 1-based. SUBSTRING("HELLO", 1, 2) returns "HE", not "EL". Some languages are 0-based; Cambridge is not.

❌ Closing nested loops with the wrong NEXT variable

Every FOR needs a matching NEXT with the same variable name. Nested loops need TWO NEXTs — inner one first, then outer. "closing the nested loops with NEXT statements" (2025 w25 examiner report) — students forget the inner NEXT.

❌ LENGTH as index vs count

LENGTH("hello") returns 5 — the count. That's the SAME as the last valid position (because Cambridge is 1-based). Careful when using LENGTH in loop ranges — FOR i <- 1 TO LENGTH(s) visits every character.

📋 Cambridge Exam Focus

Mark-winning tips from the 2023–2025 examiner reports:

Choose the right loop. FOR = fixed count, WHILE = check first (0+ runs), REPEAT = run then check (1+ runs).
CASE always needs OTHERWISE. Non-negotiable in Cambridge pseudocode.
Close every FOR with a matching NEXT. Nested loops need two NEXTs — inner first, then outer.
SUBSTRING(str, start, length) — start is 1-based. Length is a count, not an end position.
LENGTH returns a count. Also equals the last valid position (Cambridge is 1-based).
Counter starts at 0, increments by 1 when condition met. Totaller starts at 0, adds Value each iteration.
When explanation required, don't answer with pseudocode. Examiners flag this as recurring.
When tracing loops, show every iteration through to full completion. Not stopping short.

🎯 Quick Knowledge Check

Tap each question to reveal the answer. Aim for at least 5 of 6.

1. What are the three iteration constructs in Cambridge pseudocode?
FOR (count-controlled), WHILE (pre-condition), REPEAT UNTIL (post-condition).
2. Which loop is guaranteed to run at least once?
REPEAT UNTIL. The condition is checked AFTER the body runs, so the body always executes once.
3. What must every CASE statement include?
An OTHERWISE branch, and ENDCASE. OTHERWISE handles values not matched by any case.
4. What is SUBSTRING("PROGRAM", 3, 4)?
"OGRA" — start at position 3 (the 'O'), take 4 characters.
5. What does LENGTH("Cambridge") return?
9. LENGTH returns the count of characters.
6. What's the difference between a counter and a totaller?
Counter counts occurrences (adds 1). Totaller sums values (adds each value).

✅ Ready for activities when you can…

Name the three loops and pick the right one. Write CASE with OTHERWISE. Trace a nested loop. Use SUBSTRING with the correct 1-based start.

Ready? Tap the 🎓 Learn tab and try the Control Flow Simulator — step through five constructs and see them run live.

📚 From the Textbook

Selection lets a program run different code depending on the data. IF handles two-way decisions and can chain into multi-way. CASE is cleaner when you're switching on a SINGLE variable's value. Iteration lets a program repeat code. Three loops exist: FOR (count-controlled), WHILE (checks before), REPEAT (checks after). Picking the right one is the difference between clean code and a bug hunt. Add the counter and totaller patterns, string manipulation with LENGTH and SUBSTRING, and the ability to nest loops inside each other — and you've got the toolkit for every Paper 2 algorithmic question.

💡 Getting Started

Draw three empty boxes labelled FOR, WHILE, REPEAT. For each of these tasks, write which loop you'd use: (1) print numbers 1 to 10; (2) keep asking for a password until it's correct; (3) roll a die until you get a 6; (4) sum an array of 20 known scores. Answers: FOR, REPEAT, REPEAT, FOR. Notice how the answer depends on whether you know the iteration count and whether the body must run at least once.

🔬 Computer Science in Context

Every real language has these three loop types (or equivalents). Python has for, while, and no direct REPEAT (you fake it with while True and break). Java, C, and JavaScript have for, while, and do...while (their REPEAT). The choice you make in Cambridge pseudocode maps directly to what you'd write on the job — the skill isn't about pseudocode, it's about picking the right control structure.

💬 Discussion

If REPEAT always runs at least once, why does WHILE exist? What kind of task specifically needs a loop that might not run at all? Give an example of code where using REPEAT instead of WHILE would cause a bug.

⚖️ WHILE vs REPEAT vs FOR — pick the right loop

The single most tested skill in this section. Ask two questions: (1) Do I know the exact count? (2) Must the body run at least once?

🎯 FOR

Use when: You know EXACTLY how many iterations.
Runs 0 times? Only if range is empty.
Syntax:
FOR i <- 1 TO 10
  OUTPUT i
NEXT i

Example use: print numbers 1–10; process an array of known size.

⏳ WHILE (pre-condition)

Use when: You don't know the count AND the body might not run at all.
Runs 0 times? Yes — if condition is false first.
Syntax:
WHILE Age < 18
  INPUT Age
ENDWHILE

Example use: input validation (may already be valid); reading a file until EOF.

🔄 REPEAT (post-condition)

Use when: You don't know the count BUT the body must run at least once.
Runs 0 times? ❌ Never — always ≥ 1.
Syntax:
REPEAT
  INPUT Password
UNTIL Password = "abc"

Example use: ask for input then check; menu that always shows once.

🌊 Control Flow Simulator — five modes, step through each

Pick a construct. Click Step. Watch the highlighted line run, state update, output print. Mode 4 (WHILE vs REPEAT) runs both loops side-by-side on the same task so you can see the pre- vs post-condition difference in one click.

Pseudocode
State

No variables yet. Click Step to begin.

Output
(nothing yet)
Click Step to begin. Each click runs one line; state and output update live.

🔤 String Toolkit — LENGTH and SUBSTRING live

Type a string. Drag the sliders. See LENGTH and SUBSTRING update in real time. The highlighted characters show what SUBSTRING extracts. Kills the two most-tested 8.10 traps: off-by-one start, and reading LENGTH as index.
1
3
LENGTH(s)
9
SUBSTRING(s, start, length)
"CAM"

📝 Cambridge syntax — quick reference

The exact syntax examiners expect.

IF (two-way)IF Age >= 18 THEN OUTPUT "Adult" ELSE OUTPUT "Minor" ENDIF
IF-ELSEIF chainIF Score >= 80 THEN Grade <- "A" ELSEIF Score >= 70 THEN Grade <- "B" ELSEIF Score >= 60 THEN Grade <- "C" ELSE Grade <- "U" ENDIF
CASE OFCASE Day OF 1: OUTPUT "Monday" 2: OUTPUT "Tuesday" OTHERWISE: OUTPUT "Weekend" ENDCASE
FOR loopFOR i <- 1 TO 10 OUTPUT i NEXT i
WHILE loop (pre)WHILE Password <> "abc" INPUT Password ENDWHILE
REPEAT loop (post)REPEAT INPUT Choice UNTIL Choice = "Q"
Counter and TotallerCount <- 0 Total <- 0 FOR i <- 1 TO 20 INPUT Score Total <- Total + Score IF Score >= 50 THEN Count <- Count + 1 ENDIF NEXT i
String functionsLen <- LENGTH("HELLO") // 5 Slice <- SUBSTRING("HELLO", 2, 3) // "ELL" Low <- LCASE("Hello") // "hello" Up <- UCASE("Hello") // "HELLO"

🎯 Six mark-scheme traps (from the examiner reports)

Trap 1 · "Another FOR loop" instead of WHILE or REPEAT

"Some candidates incorrectly attempted to rewrite the algorithm with another FOR loop." — 2025 s25 examiner report. When the task needs a condition-controlled loop (validation, keep-asking-until, unknown iterations), FOR is wrong. Use WHILE or REPEAT.

Cited: 2025 s25 examiner report — verbatim

Trap 2 · Closing nested loops with the wrong NEXT

"closing the nested loops with NEXT statements" — 2025 w25 examiner report. Every FOR needs its matching NEXT with the same variable. Nested loops have TWO NEXTs — inner one first, then outer. Skipping either loses marks.

Cited: 2025 w25 examiner report — verbatim

Trap 3 · Answering with pseudocode when explanation required

"Some candidates incorrectly answered the question using pseudocode only. The question required an explanation." — 2025 s25 examiner report. If the question asks you to explain, write words. Pseudocode alone doesn't score explanation marks.

Cited: 2025 s25 examiner report — verbatim

Trap 4 · Not showing every iteration in a trace

"A common error amongst nearly correct solutions was not providing enough evidence to show all the iterations of the algorithm through to its full completion." — 2024 s24 examiner report. Trace every iteration. Don't summarise.

Cited: 2024 s24 examiner report — verbatim

Trap 5 · Missing OTHERWISE in CASE

Cambridge CASE statements require an OTHERWISE branch. It's the default that fires when no case matches. Leaving it out is a syntax error in Cambridge pseudocode.

Cited: syllabus requirement (0478)

Trap 6 · SUBSTRING off-by-one on start position

Cambridge SUBSTRING is 1-based. SUBSTRING("HELLO", 1, 2) = "HE". Some students carry over 0-based habits from Python/Java — that's wrong here.

Cited: 2025 s25 SUBSTRING question
Path

Topic 8.6–8.11 Learning Journey

Mistakes

Mistakes log

Progress

Stats & graphs

0%Accuracy
0Answered
0Streak
Bookmarks

Bookmarks

My Notes

My Notes

Title
Note
Knowledge Vault 2.0

Knowledge Vault

Add entry

Category
Confidence
Title
Info

Entries

🎮 Drill 1 — Loop Picker

A task is described. Pick the RIGHT loop: FOR, WHILE, or REPEAT.

🎮 Drill 2 — IF Chain Tracer

Given an IF/ELSEIF chain and a variable value, which branch runs?

🎮 Drill 3 — Nested Loop Counter

Given nested loops, how many times does the inner body run in total?

🎮 Drill 4 — String Slice Predictor

Given a SUBSTRING call, what's the result?

🎮 Drill 5 — 60-Second Cascade Sprint

10 rapid questions on loops, selection, strings, nesting. Beat your best.

60
0 / 0

✎ Practice — 20 MCQs covering 8.6 – 8.11

Filter:

📋 Exam Mode — Cambridge-style questions

Every question below is drawn from a real Cambridge Paper 2 (2022–2025) or the examiner report describing it. Type your answer, then reveal the model.

🔄 Traps — mark-scheme wording

Trap · "Another FOR loop" trap

When the task needs condition-based iteration (validation, keep-asking-until), students force a FOR. Use WHILE or REPEAT.

2025 s25 examiner report — verbatim

Trap · Nested loop NEXT closure

Every FOR needs its matching NEXT (same variable). Nested loops need TWO NEXTs — inner first, then outer.

2025 w25 examiner report — verbatim

Trap · Answering with pseudocode when explanation required

Question asks to explain? Write words. Pseudocode alone doesn't score explanation marks.

2025 s25 examiner report — verbatim

Trap · Not showing every iteration in a trace

"Not providing enough evidence to show all the iterations of the algorithm through to its full completion." — 2024 s24. Every iteration.

2024 s24 examiner report — verbatim

Trap · Missing OTHERWISE in CASE

Cambridge CASE requires OTHERWISE. It's the default. Without it, unmatched values have no defined behaviour.

0478 syllabus requirement

Trap · SUBSTRING off-by-one on start

Cambridge SUBSTRING is 1-based. Position 1 = first character. Not 0-based like Python.

2025 s25 SUBSTRING question

Trap · WHILE loop that never terminates

If the WHILE condition never becomes false, the loop runs forever. Make sure the body changes something that eventually makes the condition false.

Common Paper 2 mistake

Trap · Confusing IF branch order

In IF-ELSEIF chains, only the FIRST matching branch runs. Order the conditions from most specific to most general (e.g. Score >= 80 before Score >= 50).

Common Paper 2 mistake

Trap · Combining loop conditions wrong

"WHILE X AND Y" continues only while BOTH are true. "WHILE X OR Y" continues while EITHER is true. Wrong operator = wrong exit behaviour.

Recurring across 2023–2025

🧠 Memory triggers

WRF — three loops

The iteration types.
WHILE (pre-condition, 0+ runs) · REPEAT (post-condition, 1+ runs) · FOR (count-controlled).

Pre / Post / Fixed

Loop choice by check timing.
Pre-condition → WHILE (check first). Post-condition → REPEAT (run then check). Fixed count → FOR.

CASE needs OTHERWISE

CASE always has a default.
Miss OTHERWISE = miss marks. Every CASE OF gets OTHERWISE before ENDCASE.

SUBSTRING(str, START, LEN)

1-based, length is a count.
SUBSTRING("HELLO", 1, 2) = "HE". Start=1 for first character. Length=count, not end position.

Counter starts 0, Totaller starts 0

The two accumulator patterns.
Counter: Count <- Count + 1 when condition met.
Totaller: Total <- Total + Value every iteration.

🏆 Skill grid

Green = secured (≥70%). Yellow = focus (30–69%). Grey = not attempted. Tap any badge to override.

✔ Saved