Lecture Notes — Lecture 06: Traces and Loop Reasoning

Companion to the lecture plan and the worked examples. Read the Definitions before class, the Explanation after it; the practice questions and the lecture quiz close the loop.

Definitions

Explanation

The state table is the skill. Columns: one per variable, plus the loop condition. Rows: one per pass. Fill it honestly, row by row - 'mental tracing' is where mistakes hide. The table is also the fastest known way to find off-by-one bugs.

Loop anatomy. Initialisation (before), condition (checked before every pass), body, update (the line that moves the loop toward termination). Most loop bugs live in initialisation or update, not in the condition where people look first.

Invariants in one sentence. Say what is true at the top of every pass ('the total includes the first i numbers'). If you can say that, you can argue correctness; if you cannot, you do not yet understand your own loop.

Nested loops and grids. The inner loop runs fully per outer pass: i outer, j inner visits i × j cells. Draw the grid, colour visited cells, then count - this picture is the honest basis for lecture 17's cost arithmetic.

Termination as a proof habit. Name the shrinking quantity. If none exists, you have an infinite loop, and the table will show it: some column stops changing while the condition stays true.

Examples

The lecture's worked examples live in examples.md; the case studies this lecture builds on are worked in class from the projector. The case sequence with difficulties:

Common misconceptions

Summary and key takeaways

  1. One row per pass, one column per variable, condition included.
  2. Bugs live in initialisation and update more often than in conditions.
  3. Say the invariant; it is your correctness argument.
  4. Nested loops are grids: outer × inner cells.

Practice questions

Where this leads

Next lecture: Debugging as a Method. The quiz below checks this lecture's essentials before we build on them.