Problem Solving — CS & DS
Lecture 06 — Traces and Loop Reasoning
Learning objectives
- Trace loops with a variable table
- Predict loop outputs before running code
- Identify off-by-one errors systematically
Case-based lecture: you attempt, we discuss, then we reveal.
Today
The plan
- Four cases:
cs-021, cs-022, cs-023, cs-024 - Each: 5-minute attempt → discussion → reveal → prompt
- Worked examples in between — ask anything
- Break mid-lecture · exit question at the end
Key definitions
Key definitions
- Trace table (state table) — one row per loop pass; one column per variable the loop reads or writes.
- Loop condition — the boolean that decides whether another pass happens; it belongs in the table.
- Off-by-one error — a loop that runs once too often or too few; two classic causes are boundary mix-ups (≤ vs <) and wrong initialisation.
- Nested loop — a loop inside a loop; the inner loop runs fully for every outer pass.
- Invariant (informal) — a statement that is true before and after every pass; why the loop's answer is right.
- Termination — the proof a loop ends: name a quantity that strictly decreases (or increases) and is bounded.
Explain each in one breath; the cases will do the heavy lifting.
Worked example
Trace the tally: loop reasoning on paper
cs-021Sum the numbers 1..12, skipping multiples of 3. Predict first, then trace the loop table.
Expected: 48
Cost: O(limit). Skipped items cost a condition check but no addition - skipping is not free.
Worked example
Nested loops, traced honestly
cs-023With n = 4 rows and the rule 'star when column <= row else dot', what does the double loop print? Trace row 2 by hand.
count = 0
for row in range(4):
for col in range(3):
count += 1
print(count)
Expected: four lines: * then **. then ***.. then ****...
Cost: O(n^2) characters - the sum 1 + 3 + 5 + ... + (2n - 1) = n^2 is the doubling-grid fact from the lecture.
Case attempt · lecture 06
Case cs-021 · BeginnerTrace the Tally
A short accumulator loop with a twist (skip multiples of 3). Predict output by trace table, then verify.
**Input:** numbers 1..12, skip multiples of 3**Output:** sum 1+2+4+5+7+8+10+11 = 48Solve for the worked instance first. Then ask what would change if onenumber, name, or condition were replaced by something stranger.
⏱ 5 minutes — attempt nowPseudocode, flowchart or Python. State one assumption. Compare with your neighbour at minute 4.
Discussion
cs-021 — discuss
- What did the deciding quantity turn out to be?
- Which assumption shaped your answer?
- After the solution is revealed, the class spends five minutes on this
prompt: **"Which accumulator was hardest to get right, and what test would have caught the mistake?"**
Instructor: the reveal, the reasoning section and common wrong turns are in the instructor distribution for cs-021 — not embedded in this deck.
Case attempt · lecture 06
Case cs-022 · FoundationalThe Shrinking Loop
A loop divides a number while it is even. How many iterations for a given input, and when does it terminate? Build the trace and the general rule.
**Input:** n = 96**Output:** 96->48->24->12->6->3 (stop, odd): 5 divisions, 6 values seenSolve for the worked instance first. Then ask what would change if onenumber, name, or condition were replaced by something stranger.
⏱ 5 minutes — attempt nowPseudocode, flowchart or Python. State one assumption. Compare with your neighbour at minute 4.
Discussion
cs-022 — discuss
- What did the deciding quantity turn out to be?
- Which assumption shaped your answer?
- After the solution is revealed, the class spends five minutes on this
prompt: **"Where exactly would this solution break first if the input grew to a million items — and would anything break at all?"**
Instructor: the reveal, the reasoning section and common wrong turns are in the instructor distribution for cs-022 — not embedded in this deck.
Case attempt · lecture 06
Case cs-023 · IntermediateNested and Confused
Two nested loops with a conditional print. Predict the exact output pattern; then generalise to n lines. Pure trace discipline.
**Input:** n = 4 (rows); inner prints star when col <= row else dot**Output:** row1 '*'; row2 '**.'; row3 '***..'; row4 '****...' - each row adds one extra '*' and one extra '.'Solve for the worked instance first. Then ask what would change if onenumber, name, or condition were replaced by something stranger.
⏱ 5 minutes — attempt nowPseudocode, flowchart or Python. State one assumption. Compare with your neighbour at minute 4.
Discussion
cs-023 — discuss
- What did the deciding quantity turn out to be?
- Which assumption shaped your answer?
- After the solution is revealed, the class spends five minutes on this
prompt: **"Which accumulator was hardest to get right, and what test would have caught the mistake?"**
Instructor: the reveal, the reasoning section and common wrong turns are in the instructor distribution for cs-023 — not embedded in this deck.
Case attempt · lecture 06
Case cs-024 · AdvancedThe Off-By-One Museum
Three near-identical loops that each misbehave by one step. Diagnose each, fix minimally, and state the lesson each artefact teaches.
**Input:** three loops: (a) range(1, n) summing 1..n, (b) while i <= n: i += 2 summing 1..n, (c) i = n; while i > 0: i -= i // 4 + 1**Output:** the diagnosis: (a) misses the last value n; (b) visits only odd i, so every even value is skipped; (c) terminates, with a step count that grows logarithmicallySolve for the worked instance first. Then ask what would change if onenumber, name, or condition were replaced by something stranger.
⏱ 5 minutes — attempt nowPseudocode, flowchart or Python. State one assumption. Compare with your neighbour at minute 4.
Discussion
cs-024 — discuss
- What did the deciding quantity turn out to be?
- Which assumption shaped your answer?
- After the solution is revealed, the class spends five minutes on this
prompt: **"Where exactly would this solution break first if the input grew to a million items — and would anything break at all?"**
Instructor: the reveal, the reasoning section and common wrong turns are in the instructor distribution for cs-024 — not embedded in this deck.
Check yourself
Common misconceptions
- Tracing in the head - the table exists precisely because heads lie.
- Omitting the loop-condition column, then wondering why termination is unclear.
- Fixing the condition when the bug is the initialisation (and vice versa).
- Assuming nested loops always multiply costs - they do, but say it with the grid, not as a slogan.
Summary
Summary & exit question
- Named technique today: Traces and Loop Reasoning
- Four cases attempted — methods before answers
Exit question (choose one, 60 seconds)
- What belongs in every column of a state table?
- Give the two classic off-by-one causes.
- When does a nested loop's inner count matter most?
Expected answers (instructor): every variable whose value the loop reads or writes, plus the loop condition boundary (≤ vs <) and initialisation (starting one early/late) when estimating cost: it multiplies, so grid thinking exposes growth