An infinite loop occurs when a loop's termination condition is never reached, so the loop continues indefinitely. Avoid one by ensuring that each iteration changes the program state toward a reachable stopping condition.
Why Infinite Loops Occur
A loop requires an initialized control variable or state, a Boolean condition controlling repetition, and an update that eventually makes the condition false.
For example, this loop never changes i, so i < 5 always remains true:
i = 0
WHILE i < 5
OUTPUT i
ENDWHILE
The corrected version makes progress toward termination:
i = 0
WHILE i < 5
OUTPUT i
i = i + 1
ENDWHILE
| Cause | How to avoid it |
|---|---|
| The control variable is not updated | Update it inside the loop body. |
| The update moves away from termination | Check the direction and size of the update. |
| The condition can never become false | Confirm that the stopping value is reachable. |
| A sentinel value is never entered or read | Update the input within the loop and validate it. |
| An equality test misses a value | Prefer a suitable boundary condition, such as i >= limit, when exact equality is not guaranteed. |
A break statement is unreachable | Check the selection logic leading to break. |
A common misconception is that any long-running loop is infinite. It may simply be inefficient or process large input; an infinite loop has no reachable termination. Deliberate continuous event loops instead require controlled event handling or an exit mechanism.
IB Exam Technique
For a trace question, use a trace table showing the condition and variable values after each iteration. For explain or correct, identify the faulty condition or update and state why the revision terminates. Test zero iterations, one iteration, and the final permitted value.