AP® Computer Science A · Unit 2 · Topic 2.8

Trace Tables: Watching a Loop Fill In

A trace table is a grid with one column per variable and one row per loop pass, filled in with the actual values the program would compute. Writing those values down, instead of just reading the code, exposes exactly what the loop is doing and where it goes wrong.

Reading code, you see what a loop is supposed to do. Tracing it, you see what it actually does. A trace table forces you to compute each value by hand, one pass at a time, the same way the computer would. That slows you down just enough to catch an off-by-one error, a condition that stops one pass too early, or a variable that never got updated the way you assumed.

To build one, list every variable that changes across the top, plus the loop control variable. Each row is one pass through the loop body: check the condition, run the statements in order, write down the new value of each variable, then move to the next row. Stop adding rows the moment the condition fails — that failed check is itself worth a row, since it shows exactly why the loop ends.

This connects directly to the branching work earlier in the unit: a trace table is really a record of which branch or body got executed on each pass, with the variable values as proof. It also sets up the next step, where you stop tracing by hand and instead reason about a loop's final state directly — spotting patterns like a running sum or a doubling value and writing a closed-form answer instead of rows.

Key terms

trace table
A table with one column per variable and one row per loop pass, used to track a program's state step by step.
loop control variable
The variable a loop tests each pass to decide whether to continue, such as i in a for loop.
pass
One complete execution of a loop body, from the condition check through the update.
closed-form expression
A single formula that gives a loop's final result directly, without needing to simulate each pass.

Watch it explained

  1. How it worksHow does a trace table give one column per variable and one row per pass?
  2. Worked exampleBuild a trace table for int s = 0; for (int i = 1; i ≤ 4; i++) s += i;
  3. Worked exampleBuild a trace table for a loop that doubles x from 1 while x stays under 100.
  4. Going furtherWhat changes in a trace table when a second variable only updates on some passes?

Check yourself

Your turn1 of 2
A loop runs int s = 0; for (int i = 1; i ≤ n; i++) s += i; Write a closed-form expression, in terms of n, for the final value of s — no loop or conditional allowed.

End of topic.