01 / 21

Tracing Loops
in Java

Learn to step through loop execution line by line, track variable changes, and predict program output with confidence.

Java AP Computer Science A

What Is Tracing?

Tracing means simulating the computer: you follow code line by line, recording how each variable changes at every step. Instead of guessing what a program does, you become the runtime and execute it on paper.

Read
Identify the loop type, condition, and body.
Record
Write down each variable's value after every iteration.
Resolve
Determine the final output or return value.

The Three Java Loops

for Loop
Best when you know the exact number of iterations. Init, condition, and update all in one line.
while Loop
Best when you don't know how many times to iterate. Checks condition before each iteration.
do-while Loop
Guarantees at least one execution. Checks condition after the body runs.

Anatomy of a for Loop

for (int i = 0; i < 5; i++) {
  System.out.print(i + " ");
}
Initialization int i = 0 Condition
\(i < 5\)
Body print(i) Update
\(i\text{++}\)
repeat

Loop Execution Flow

Initialize Condition true? Yes Execute Body Update No End

for vs while vs do-while

for while do-while
Condition check Before body Before body After body
Minimum runs 0 0 1
Update location In header Inside body Inside body
Best when Count known Count unknown Run at least once

How to Build a Trace Table

1
List all variables as column headers, plus columns for "Condition" and "Output."
2
Write initial values in the first row (before the loop starts).
3
Evaluate the condition. Write true or false.
4
If true, execute the body. Record any output produced and update variable values.
5
Apply the update (e.g., i++). Record the new value and go back to step 3.
6
When condition is false, stop. The last row shows final variable values and total output.

Example 1: Simple Counter

int sum = 0;
for (int i = 1; i <= 4; i++) {
  sum += i;
}
System.out.println(sum);
IterationiCondition \(i \le 4\)sum (after update)
(init)--0
11true1
22true3
33true6
44true10
(exit)5false10

Example 2: while Loop Tracing

int n = 64;
int count = 0;
while (n > 1) {
  n /= 2;
  count++;
}
System.out.println(count);
Iterationn\(n > 1\)count
Init64true0
132true1
216true2
38true3
44true4
52true5
(exit)1false6

Example 3: Nested Loops

String result = "";
for (int i = 1; i <= 3; i++) {
  for (int j = 1; j <= 2; j++) {
    result += "(" + i + "," + j + ")";
  }
}
ijOutput appended
11(1,1)
12(1,2)
21(2,1)
22(2,2)
31(3,1)
32(3,2)

The Off-by-One Problem

The most common loop bug: your loop runs one too many or one too few times because of incorrect boundary conditions.

// Prints 0 1 2 3 4 (5 values)
for (int i = 0; i < 5; i++)

// Prints 0 1 2 3 4 5 (6 values)
for (int i = 0; i <= 5; i++)

Tracing Accumulators

An accumulator is a variable that builds up a result across iterations: a running sum, product, or concatenated string. Tracing accumulators requires tracking the value before and after each operation.

int product = 1;
for (int i = 1; i <= 5; i++) {
  product *= i;
}
// product = 1*1*2*3*4*5 = 120 (5!)
iproduct (before)product (after)
111
212
326
4624
524120

Tracing String Building

String s = "ABCDE";
String rev = "";
for (int i = s.length() - 1; i >= 0; i--) {
  rev += s.charAt(i);
}
icharAt(i)rev
4E"E"
3D"ED"
2C"EDC"
1B"EDCB"
0A"EDCBA"

Spotting Infinite Loops

An infinite loop occurs when the condition never becomes false. Tracing 2-3 iterations will reveal if the variable isn't moving toward termination.

// BUG: n never changes!
int n = 10;
while (n > 0) {
  System.out.println(n);
  // Missing: n--;
}

Common Mistakes

✕ Forgetting the Update
Missing i++ in a while loop causes an infinite loop. The for loop header makes this harder to forget.
✕ Off-by-One Boundary
Confusing \(<\) with \(\le\). Always trace the last iteration to verify the boundary value.
✕ Wrong Initial Value
Starting a sum at 1 instead of 0, or a product at 0 instead of 1, corrupts the accumulator.
✕ Scope Confusion
A variable declared inside a loop resets every iteration. Move it before the loop to accumulate.

Tracing Cheat Sheet

Concept What to Check Key Question
Initialization Starting values of all variables Sum starts at 0? Product at 1?
Condition \(<\) vs \(\le\) boundary Does the last iteration include the boundary?
Body What changes each iteration Which variables are modified?
Update How the loop variable changes Does it approach termination?
Termination Final values after loop exits What is the last value of \(i\)?

Question 1 of 5

What is the value of x after the loop finishes?

Question 2 of 5

What does this code print?

Question 3 of 5

How many times does the loop body execute?

Question 4 of 5

What is printed?

Question 5 of 5

What is the output of this do-while loop?