AP® Computer Science Principles · Big Idea 3 · Topic 3.8

Infinite Loops and Off-by-One Errors

An infinite loop runs forever because its stopping condition never becomes true, while an off-by-one error runs one too many or too few times because the condition is checked against the wrong value.

A loop needs two things to stop correctly: a condition that depends on something changing, and code inside the loop that actually changes it. If the counter never updates, or the condition is written so it can never flip from true to false, the loop has no way out. The computer isn't struggling or thinking hard. It is doing exactly what it was told, over and over, because the instructions never gave it a reason to stop.

Off-by-one errors are a milder version of the same idea: the loop does stop, just at the wrong moment. If a loop is meant to run 10 times starting the counter at 1 and stopping when the counter passes 10, but the stopping condition says 'while counter ≤ 11' instead of 'while counter ≤ 10', the loop runs 11 times, one more than intended. The bug usually hides in the comparison operator: using ≤ instead of <, or starting the count from 0 instead of 1 without adjusting the limit.

Both errors come from the same place as the rest of Big Idea 3: a loop is only as reliable as its stopping condition. Once a program can loop, it can also fail to stop, which connects directly to the idea that some problems cannot be fully checked by any algorithm in advance. Careful tracing, running through the loop by hand and counting iterations, catches both bugs before they cause a frozen or miscounted program.

Key terms

infinite loop
A loop whose stopping condition never becomes false, so it repeats forever.
off-by-one error
A bug where a loop runs one time too many or too few because of an incorrect comparison or starting value.
stopping condition
The test checked before or during each loop pass that decides whether the loop continues or ends.
loop counter
A variable that tracks progress through a loop and must be updated inside it to eventually satisfy the stopping condition.

Watch it explained

  1. How it worksHow does a loop counter that never reaches its target create an infinite loop?
  2. Worked exampleFind the bug in a loop meant to run 10 times that repeats 11 times instead.
  3. Going furtherWhat happens to a loop when the variable in its stopping condition is never updated inside it?
  4. Common mistakeWhy isn't a frozen program always a sign that the computer is just slow?

Check yourself

Your turn1 of 2
A loop meant to run 70 times has an off-by-one bug that makes it run one extra time. How many times does the buggy loop actually run?

End of topic.