← Back to course

Algorithms & Tracing

You’ll be able to

Tracing is careful bookkeeping

To trace an algorithm, walk through it one statement at a time, writing down the new value of every variable after each step. Do not skip ahead or guess — the whole skill is patient bookkeeping. A trace table with a column per variable and a row per step makes the final answer fall out reliably.

Loops that step by more than one

When a loop variable changes by more than 1 — say x -= 3 — the number of iterations is not obvious. Trace it: track the value each pass and stop when the condition fails. Miscounting these is the classic off-by-one error, so always check the last pass explicitly rather than estimating.

Swapping two values

To exchange the contents of two variables you need a temporary holder, because a direct a = b would overwrite a before you saved it. The standard three-step swap is temp = a; a = b; b = temp;. After it runs, a holds the old b and b holds the old a.

Three-step swap
temp = a; a = b; b = temp;
The temporary variable preserves the first value so it is not lost when the second is copied in.
Worked example

How many times does the loop run? int x = 10; then int count = 0; then while (x > 0) { x -= 3; count++; } then System.out.println(count);

  1. 1.Start x = 10, count = 0. Pass 1: x > 0 is true, x becomes 7, count 1.
  2. 2.Pass 2: 7 > 0 true, x becomes 4, count 2. Pass 3: 4 > 0 true, x becomes 1, count 3.
  3. 3.Pass 4: 1 > 0 true, x becomes -2, count 4.
  4. 4.Now x = -2, so x > 0 is false and the loop stops.
Answer: It prints 4: the loop runs four times before x drops to -2 and the condition fails.
Checkpoint

What does this print? `int x = 10;` then `int count = 0;` then `while (x > 0) { x -= 3; count++; }` then `System.out.println(count);`

Watch out

Check the last iteration carefully. Here x becomes 1 (still > 0), so the loop runs once more, reaching -2. Stopping at x = 1 would give the off-by-one answer 3.

Checkpoint

What does this print? `int a = 3;` then `int b = 7;` then `int temp = a;` then `a = b;` then `b = temp;` then `System.out.println(a + " " + b);`

On the exam

For swap questions, resist the urge to assume a = b overwrites both. Trace all three statements: the temporary variable is what makes the exchange work correctly.

Answer the 2 checkpoints as you read.

Sign in to save your progress