CS
Topic 7 Algorithms & debugging · 7.7 · 7.8 · 7.9 · 7.10

Algorithms & Debugging

You've designed programs. Now watch them run, trace their state, work out what they do, and fix them when they break. Common algorithms, trace tables, finding purpose, hunting errors — the four skills that separate solid Paper 2 candidates from great ones.

🧪 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 to feel confident before the Trace Table Runner and Bug Hunter. When you're ready, tap 🎓 Learn.

🎯 Topic Overview

You've spent Topic 7.1–7.6 designing programs. Now you'll run them. That means recognising the five common algorithms Cambridge tests (linear search, bubble sort, max, min, average), tracing an algorithm step by step in a table, working out what an algorithm does just by reading it, and finding and fixing errors. Every Cambridge Paper 2 asks a trace-table question — it's the most reliable mark-earner on the paper, and the hardest to bluff.

🎓 Learning Objectives

By the end of Topic 7.7–7.10 you should be able to…

  • Recognise and describe the five common algorithms: linear search, bubble sort, max, min, average
  • Use counter and totaller (accumulator) variables correctly
  • Complete a trace table for any given algorithm, recording every variable change
  • Follow nested loops without losing track of the outer variables
  • State the purpose of an algorithm in one sentence, just from its pseudocode
  • Find and correct syntax, logic and runtime errors in a program

📖 Key Terminology

TermOne-line definition
AlgorithmA sequence of steps to solve a problem.
Trace tableA table used to step through an algorithm and record every variable value.
Linear searchCheck each element in turn until the target is found or the list ends.
Bubble sortCompare adjacent pairs; swap if out of order; repeat until no swaps.
CounterA variable that counts occurrences (e.g. how many pass a test).
TotallerA variable that accumulates a running total (also called an accumulator).
IterationOne pass of a loop.
Nested loopA loop inside another loop (bubble sort's core pattern).
FlagA BOOLEAN variable that signals "done" or "found" — often used to exit a loop early.
Syntax errorCode that breaks the rules of the language (missing ENDIF, wrong keyword).
Logic errorCode that runs but produces the wrong result (> instead of >=).
Runtime errorCode that fails while running (dividing by zero, array out of bounds).

🧠 Core Theory

The five common algorithms

AlgorithmWhat it doesCore pattern
Linear searchCheck each element; stop when foundLoop + IF + flag
Bubble sortRepeatedly swap adjacent pairsNested loop + swap
MaxTrack the largest value seenLoop + IF (>)
MinTrack the smallest value seenLoop + IF (<)
AverageSum + count then divideTotaller ÷ counter

Three types of programming error

TypeMeaningExample
SyntaxBreaks the language rulesMissing ENDIF; NEXT j when the loop was FOR i
LogicCode runs but gives wrong resultUsing > when you meant >=; outputting the wrong variable
RuntimeFails during executionDividing by zero; accessing Array[11] in a 10-element array

Trace table rules (the ones examiners flag)

✎ Record every variable assignment — never skip.
No quotation marks around output values in the Output column.
✎ Once the algorithm ends (loop exits), stop tracing. No further rows.
✎ Trace all given input data — not just the first value.
✎ Leave a cell blank if that variable didn't change on that step.

💡 Worked Examples

Example 1 · Trace the Max algorithm

Given Numbers = [23, 41, 17, 88, 5] and this algorithm:

Max <- Numbers[1]
FOR i <- 2 TO 5
    IF Numbers[i] > Max THEN
        Max <- Numbers[i]
    ENDIF
NEXT i
OUTPUT Max

The trace table:

iNumbers[i]MaxOutput
23
24141
317
48888
55
88

Note: no quotation marks on 88. Blank cells where variables don't change.

Example 2 · What does this algorithm do?

Count <- 0
FOR i <- 1 TO 30
    INPUT Score
    IF Score >= 50 THEN
        Count <- Count + 1
    ENDIF
NEXT i
OUTPUT Count

Purpose (in one sentence): It counts how many of 30 input scores are 50 or greater (i.e. how many passed).

Notice the pattern: Count is a counter. The IF is a filter. Loop 30 times = process 30 items.

⚠️ Common Misconceptions

❌ Putting quotation marks around trace outputs

The trace table Output column stores values, not strings-as-text. Write Found at 3, not "Found at 3". Examiners deduct for the quotes.

❌ Continuing the trace past the loop exit

Once the algorithm's stopping condition is met, no further rows go in the trace table. A WHILE that exits at i=6 doesn't get a row for i=7.

❌ Describing the code line by line instead of the overall purpose

"It sets Count to 0, then loops from 1 to 30…" is reading the code back, not stating its purpose. Say what it does: "It counts how many scores are ≥ 50."

❌ Bubble sort with only one loop

Bubble sort needs a nested loop: outer for passes, inner for comparisons. A single loop sorts only one pair, not the whole list.

❌ Skipping a variable in the trace when it doesn't change

Leave the cell blank — but don't remove the row. Every iteration gets a row; unchanged variables just don't get a value.

📋 Cambridge Exam Focus

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

Record every assignment in the trace table — never skip a variable change.
No quotes on outputs — the Output column stores values, not string literals.
Stop when the algorithm stops — no rows after the loop exit condition is met.
Trace all the given input data, not just the first value.
Purpose = one sentence stating what the algorithm does overall.
Read the code twice when hunting errors: pass 1 for syntax, pass 2 for logic.
Bubble sort needs nested loops — always. And a flag to exit early scores extra marks.

🎯 Quick Knowledge Check

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

1. What are the five common algorithms tested at Cambridge IGCSE?
Linear search, bubble sort, max, min, average.
2. What's the difference between a syntax error and a logic error?
Syntax = breaks the language rules (won't run). Logic = runs but gives the wrong result.
3. Should trace-table outputs be wrapped in quotation marks?
No — never. The Output column stores values, not string literals.
4. What does a counter do?
It counts how many times something occurs (starts at 0, increments by 1 each time).
5. Why does bubble sort need nested loops?
Outer loop = number of passes. Inner loop = comparisons within each pass. A single loop only sorts one adjacent pair.
6. How do you describe the purpose of an algorithm?
One sentence stating what it does overall — not reading the code line by line.

✅ Ready for activities when you can…

Name the five common algorithms. Know the three error types (syntax, logic, runtime). Follow every trace-table rule (record every assignment, no quotes on outputs, stop at loop exit). State an algorithm's purpose in one sentence.

Ready? Tap the 🎓 Learn tab and try the Trace Table Runner — step through three real algorithms and watch the variables update live.

📚 From the Textbook

Five algorithms cover almost every Cambridge Paper 2 question: linear search (check each item until found), bubble sort (repeatedly swap adjacent pairs), and three accumulator patternsmax, min and average. Every one of them is tested by tracing — stepping through the code with sample data and recording every variable in a table. If you can trace it, you understand it. Trace tables also help you spot two things: the purpose of an unfamiliar algorithm (7.9) and the errors in a buggy one (7.10). Get comfortable with tracing and this whole section opens up.

💡 Getting Started

Grab a pen and paper. Copy the Max algorithm from Book Notes. Pick your own array of 5 numbers. Draw a trace table with columns for i, Numbers[i], Max, Output. Step through by hand — one row per iteration. If your Max ends as the largest number in your list, you've done it right. That's the skill every trace-table question tests.

🔬 Computer Science in Context

Debuggers in real IDEs (VS Code, PyCharm, Visual Studio) are essentially live trace tables. You set a breakpoint, run the program, and the IDE shows you every variable's current value, stepping through one instruction at a time. Learning trace tables is learning how to think like a debugger — a skill you'll use every day as a professional programmer.

💬 Discussion

Bubble sort is famously inefficient on large data (O(n²)) — modern languages use quicksort or Timsort instead. So why does Cambridge still teach bubble sort? What is the educational value of an "inefficient" algorithm?

⚠️ Three kinds of error — know them apart

Every Paper 2 error-hunting question expects you to identify the type as well as fix the bug. Get the type right and the fix follows.

🔧 Syntax

What: code that breaks the language rules.
When: caught by the compiler/interpreter before the program even runs.
Examples: missing ENDIF, NEXT j when the loop is FOR i, misspelled keyword.

🎯 Logic

What: code that runs but produces the wrong answer.
When: only visible when you test with data.
Examples: > where you meant >=, outputting the wrong variable, off-by-one in a loop range.

💥 Runtime

What: code that fails while running.
When: program crashes mid-execution.
Examples: dividing by zero, accessing Array[11] in a 10-element array, reading a file that doesn't exist.

📊 Trace Table Runner — step through algorithms live

Pick an algorithm, click Step, watch the current line highlight and the trace table build up row by row. This is the exact skill every Paper 2 trace-table question tests.

Pseudocode
Trace table
Click Step to begin. The highlighted line shows the instruction that just ran; the trace table row shows what changed.

🐛 Bug Hunter — spot the errors

The program below is meant to find the highest of 5 scores. It has 3 bugs. Click any line you think has an error. You get instant feedback. Try to find all 3.
🎯 Bugs found: 0 / 3
Click any line to make a guess.

📝 Common Algorithms — Cambridge reference

The five patterns you must recognise. Learn to spot them at a glance.

🔍 Linear SearchFound <- FALSE i <- 1 WHILE Found = FALSE AND i <= N IF List[i] = Target THEN Found <- TRUE OUTPUT i ENDIF i <- i + 1 ENDWHILE
🫧 Bubble SortFOR i <- 1 TO N - 1 FOR j <- 1 TO N - i IF List[j] > List[j+1] THEN Temp <- List[j] List[j] <- List[j+1] List[j+1] <- Temp ENDIF NEXT j NEXT i
🔺 Find MaximumMax <- List[1] FOR i <- 2 TO N IF List[i] > Max THEN Max <- List[i] ENDIF NEXT i OUTPUT Max
🔻 Find MinimumMin <- List[1] FOR i <- 2 TO N IF List[i] < Min THEN Min <- List[i] ENDIF NEXT i OUTPUT Min
📊 Average (totaller ÷ counter)Total <- 0 FOR i <- 1 TO N INPUT Value Total <- Total + Value NEXT i Average <- Total / N OUTPUT Average
🧮 Counter (count matches)Count <- 0 FOR i <- 1 TO N IF List[i] >= Threshold THEN Count <- Count + 1 ENDIF NEXT i OUTPUT Count

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

Trap 1 · Quotation marks on trace outputs

The Output column stores values, not strings. Write Found at 3, not "Found at 3". Examiners deduct for the quotes every session.

Cited: 2025 s25 · 2024 w24 — identical wording in both reports

Trap 2 · Continuing the trace past the loop exit

Once the stopping condition is met, no further rows go in the trace table. A WHILE that exits at i=6 doesn't get a row for i=7.

Cited: 2025 s25 · 2024 w24

Trap 3 · Not recording every variable assignment

"When tracing an algorithm, each time a variable has a value assigned to it, this needs to be recorded in the trace table." — Cambridge examiner report 2024 w24.

Cited: 2024 w24 examiner report

Trap 4 · Describing the code line by line instead of the overall purpose

Cambridge wants ONE sentence stating the overall goal — not a walkthrough of every line. "It counts how many scores pass" scores; "It sets Count to 0, then loops 30 times, then…" doesn't.

Cited: 2023 w23 Q4(b), 2024 s24 Q3(b)

Trap 5 · Bubble sort with only one loop

"Some attempts at the bubble sort only used one loop" — 2024 w24. Bubble sort MUST be nested: outer for passes, inner for comparisons. A single loop only sorts one pair.

Cited: 2024 w24 Q12

Trap 6 · Identifying the same error twice (Yes/No swap on a decision)

"Many candidates identified the same error twice with the switching of the Yes and No on one of the decision boxes." When correcting errors, count the DISTINCT bugs, not the same bug from two angles.

Cited: 2024 w24 examiner report
Path

Topic 7.7–7.10 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 — Algorithm Identifier

A pseudocode snippet is shown. Which of the five common algorithms is it?

🎮 Drill 2 — Trace Row Predictor

Given the current row of a trace and the next instruction, what's the NEXT row?

🎮 Drill 3 — Error Type Sorter

An error is described. Is it a syntax, logic, or runtime error?

🎮 Drill 4 — Purpose Finder

A short algorithm is shown. State its purpose in one line.

🎮 Drill 5 — 60-Second Algorithm Sprint

10 rapid questions on algorithms, tracing, errors. Beat your best.

60
0 / 0

✎ Practice — 18 MCQs covering 7.7 – 7.10

📋 Exam Mode — Cambridge-style questions

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

🔄 Traps — mark-scheme wording

Trap · Quotation marks on trace outputs

The Output column stores values, not string literals. Never wrap outputs in quotes.

2025 s25 · 2024 w24 (identical wording)

Trap · Continuing the trace past the loop exit

Once the stopping condition is met, no further rows go in the trace table.

2025 s25 · 2024 w24

Trap · Missing a variable re-assignment

Every time a variable is assigned, record it. Even if the value looks the same.

2024 w24 examiner report

Trap · Only tracing the first data item

If the question gives 5 inputs, trace all 5. Do not stop after the first.

2025 s25 Q9

Trap · Describing the code line by line for "purpose"

Purpose = ONE sentence stating the overall goal. Not a walkthrough.

2023 w23 Q4(b), 2024 s24 Q3(b)

Trap · Bubble sort with only one loop

Bubble sort needs nested loops. Outer for passes, inner for comparisons.

2024 w24 Q12

Trap · Identifying the same error twice (Yes/No swap)

A decision box with swapped Yes/No labels is ONE error, not two. Count distinct bugs.

2024 w24 examiner report

Trap · Adding SQL 'ASC' to a bubble sort

SQL keywords (ASC, DESC, ORDER BY) belong in database queries — not in sort pseudocode.

2024 w24 examiner report

Trap · Endless loops from unreachable exit conditions

A WHILE that never reaches its terminal condition runs forever. Always check that the loop variable is modified inside the loop.

2024 w24 examiner report

🧠 Memory triggers

LBMMA

The five common algorithms.
Linear search · Bubble sort · Max · Min · Average.

SLR

The three error types.
Syntax (won't run) · Logic (wrong answer) · Runtime (crashes).

Trace rule of 4

The trace-table checklist.
1. Record every assignment. 2. No quotes on outputs. 3. Stop when the loop stops. 4. Blank cells for unchanged variables.

Bubble sort DNA

Nested loops + swap.
Outer loop = passes. Inner loop = adjacent comparisons. IF out-of-order → swap using a temp variable. Optional: flag to exit early when a pass makes no swaps.

Purpose = 1 sentence

State the overall goal, not the steps.
"It counts how many scores pass" ✓
"It sets Count to 0, then loops 30 times, then compares each score…" ✗

🏆 Skill grid

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

✔ Saved