AP® Computer Science A · Unit 2 · Topic 2.7

Infinite Loops and the Missing Update

An infinite loop happens when the loop's condition never becomes false, usually because the variable it depends on is never changed inside the body. The fix is an update statement that moves the variable toward the stopping condition.

A while loop checks its condition fresh before every single pass. It has no memory of how many times it has run or any sense that it's been running too long — it only asks, right now, is this condition true or false? If nothing inside the body changes the variable the condition depends on, that condition reads the same way every time, forever. The loop isn't broken in the sense of crashing. It's doing exactly what it was told: keep checking the same true thing over and over.

Trace while (n > 0) { System.out.print(n); } with n starting at 3. Pass one: n is 3, 3 > 0 is true, print 3. Pass two: n is still 3 (nothing changed it), 3 > 0 is true again, print 3. This repeats endlessly — the program never reaches a line that would change n, so it never reaches a line that would make the test false. A common confusion is thinking the loop checks its condition continuously, so it could stop mid-body the instant some value changes. It can't. The condition is only evaluated at the top of the loop, right before deciding whether to run the body again — never during the body itself.

This connects directly to how update statements work in for and while loops: an update has to move the variable toward the condition becoming false, not just change it. i++ when the test is i > 0 and i starts positive moves i further from zero, never closer — same infinite behavior, different cause. Reading a loop means checking three things together: the starting value, the test, and whether the update genuinely closes the gap between them.

Key terms

infinite loop
A loop whose condition never becomes false, so it repeats without ending.
update statement
The line inside a loop that changes the variable the condition depends on, such as n-- or i++.
loop condition
The boolean expression checked before each pass that decides whether the loop body runs again.
trace table
A row-by-row record of a variable's value through each pass of a loop, used to predict its behavior.

Watch it explained

  1. How it worksHow does an unchanging loop variable keep the condition true on every pass?
  2. Worked exampleTrace while (n > 0) { System.out.print(n); } with n starting at 3 and find why it never ends.
  3. Common mistakeWhy doesn't a loop stop the instant its condition becomes false in the middle of the body?
  4. Going furtherWhat happens when the update pushes the variable away from the stopping point?

Check yourself

Your turn1 of 2
while (n > 0) { System.out.print(n); } with no update to n inside the loop, and n starting at 3. What happens?

End of topic.