skip to content

What causes an infinite while loop and how do you ensure a loop terminates?

level: juniorimportance: must knowfreq 60%

answer

  1. Infinite = condition never false
  2. Most common cause: counter not updated
  3. Need progress toward exit each iteration
  4. while(true) is OK only with a reachable break
  5. Avoid != and float equality in conditions

basics

~20 s

A loop runs forever when its condition never becomes false. To make it terminate, the body must change something that the condition checks (like incrementing a counter) so the condition eventually turns false, or use break.

solid answer

~50 s

A while loop continues as long as its condition is true, so it becomes infinite if nothing in the body ever makes the condition false. The classic cause is forgetting to update the variable the condition depends on (e.g. checking i < n but never changing i). To guarantee termination you need progress toward the exit: each iteration must move the loop state closer to making the condition false — typically by incrementing/decrementing a counter, consuming input, or shrinking a remaining amount. Alternatively, an intentionally infinite loop like while (true) must contain a break (or return/throw) on some condition to exit. Off-by-one mistakes, wrong comparison operators, and floating-point conditions that never hit an exact value are common pitfalls. When debugging a hang, check whether the condition variable is actually mutated and whether the exit condition is reachable.

go deeper

for a junior

Identifies the missing counter update as the usual cause and adds i++ to fix it.

for a middle

Recognizes off-by-one, wrong-direction updates, and floating-point equality as termination hazards.

for a senior

Articulates the loop-variant idea (a strictly decreasing bounded quantity) and validates that exit conditions are reachable.

for a principal

Reasons about termination guarantees and total correctness, and may reference loop invariants/variants when reviewing or specifying algorithmic code.

## The contract of a loop A `while (condition)` loop keeps repeating its body **as long as `condition` is `true`**. It stops the moment the condition evaluates to `false`. Therefore a loop terminates **if and only if** something eventually makes the condition false (or an explicit exit like `break` is hit). ## Why loops become infinite An **infinite loop** is one whose condition never becomes false, so it runs forever (until the program is killed or runs out of resources). Common causes: 1. **Not updating the condition variable.** The condition reads some state, but the body never changes that state. ```java int i = 0; while (i < 5) { System.out.println(i); // i is never incremented -> infinite } ``` 2. **Updating the wrong thing / wrong direction.** Incrementing when you should decrement, or modifying a different variable than the one tested. 3. **Unreachable exit condition.** The comparison can never be satisfied — e.g. `while (i != 5)` where `i` jumps from 4 to 6. 4. **Floating-point conditions.** Doubles rarely land on an exact value, so `while (x != 1.0)` may overshoot forever. Prefer `<`/`>` bounds or integer counters. ## How to guarantee termination The key idea is **progress toward the exit**: every iteration must move the loop's state measurably closer to the point where the condition is false. Formally this is a **loop variant** — a quantity that strictly decreases (and is bounded below) each pass, like the count of remaining items. ```java int i = 0; while (i < 5) { System.out.println(i); i++; // makes progress -> i reaches 5 -> condition false -> stops } ``` Checklist for a terminating loop: - The condition depends on state that the body **changes**. - That change moves toward making the condition false (right direction). - The exit value is actually **reachable** with the step you take. ## Intentional infinite loops Sometimes you *want* an endless loop and break out from inside: ```java while (true) { String line = reader.readLine(); if (line == null) { break; // explicit exit — required, or it never ends } process(line); } ``` Here `while (true)` is fine **because** there is a reachable `break`. The same applies to `return` or throwing an exception as an exit. ## Debugging a hang If a program seems stuck in a loop: confirm the condition variable is mutated in the body, confirm the mutation direction, check for off-by-one or `!=` comparisons that can be skipped over, and verify any `break` condition can actually be reached.

  • Is while (true) bad practice?
    Not inherently. It is fine when there is a clear, reachable exit via break/return/throw inside the body — common in read loops or event loops. It is only a problem when no exit path exists or the exit is unreachable.
  • Why can while (x != target) be dangerous with doubles?
    Floating-point arithmetic is inexact, so x may never equal target exactly and steps over it. Use a range comparison like x < target or x >= target, or loop with an integer counter instead.

saying these in an interview costs you the question

  • Believing the compiler or JVM will detect and stop infinite loops — it will not.
  • Using == / != with floating-point values in loop conditions.
  • Thinking while(true) is always wrong; it's fine with a reachable break.
  • Forgetting that the condition variable must be modified inside the body, not just declared outside.

context