Algorithms & Tracing
- Hand-trace an algorithm by tracking every variable through each step
- Predict how many times a loop runs when its variable changes by more than one
- Follow a value-swap sequence using a temporary variable
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.
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.Start x = 10, count = 0. Pass 1: x > 0 is true, x becomes 7, count 1.
- 2.Pass 2: 7 > 0 true, x becomes 4, count 2. Pass 3: 4 > 0 true, x becomes 1, count 3.
- 3.Pass 4: 1 > 0 true, x becomes -2, count 4.
- 4.Now x = -2, so
x > 0is false and the loop stops.
4: the loop runs four times before x drops to -2 and the condition fails.What does this print? `int x = 10;` then `int count = 0;` then `while (x > 0) { x -= 3; count++; }` then `System.out.println(count);`
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.
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);`
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