AlgoMaster Logo

While Loop

High Priority13 min readUpdated June 2, 2026
Listen to this chapter
Unlock Audio

A while loop runs a block of code over and over as long as a condition stays true. It fits cases where the number of iterations isn't known up front, like draining a queue of pending orders or asking the customer for input until they type something valid. This lesson covers the syntax, when while is a better fit than for, and common bugs.

Syntax and Semantics

The shape of a while loop is simple:

Java evaluates the condition first. If it's true, the body runs once, and then the condition is checked again. If the condition is false the very first time, the body runs zero times and execution moves on. This is why while is called a pre-test loop: the test happens before the body, every time.

Here's a tiny example that prints the remaining stock as items get sold:

The condition remainingStock > 0 is checked, the body runs and decrements remainingStock, and the cycle repeats. When remainingStock hits 0, the condition is false and Java falls through to the line after the loop.

This diagram traces the control flow:

The arrow from "Update state" back to the condition is the key part. If the body never changes anything the condition looks at, the loop runs forever.

When to Choose while Over for

The for loop works best when the iteration count is known in advance, like "run 10 times" or "walk through every index of an array." The while loop is the better choice when the number of iterations depends on something that can change at runtime.

Three common cases:

  1. Unknown iteration count. Items are processed from a queue and the queue's size changes as work proceeds.
  2. Sentinel-driven loop. Input is read until a specific terminator value appears.
  3. Waiting for a condition to change. State is checked and an action runs when it flips.

Here's an example of case 1. The shop has a list of pending orders and the loop keeps processing them until none are left. The exact count isn't known until the loop runs:

A for loop would also work, but the while reads more naturally: keep going while there's work to do. A for loop frames the problem as "from index 0 to n", which doesn't match the shape of this task.

A running total over a varying number of cart items is another fit. The cart can have any number of products, and the loop stops when the cart is empty:

For a fixed array, a for loop is arguably cleaner here. The pattern is most useful when the source has no known length: a stream of inputs, a queue being popped, a customer who keeps adding items.

Sentinel-Controlled Loops

A sentinel value is a special marker that tells the loop to stop. The classic use is reading input until the user types a terminator. The loop doesn't know how many lines the user will enter; it keeps reading until it sees the signal.

This program asks the customer for product prices and keeps a running total. Entering 0 ends the input:

Sample interaction:

First, the loop reads one value before the loop starts, so the condition has something to check. This is called priming the loop. Second, the last statement inside the body reads the next value, which becomes the new condition input. Without that second read, the loop would test the same value forever.

Another sentinel pattern shows up when a program prompts the user repeatedly until a valid input arrives:

Sample interaction:

The initial value -1 is deliberately invalid so the loop enters at least once. Each pass re-prompts. As soon as the user types something valid, the condition fails and the loop exits.

Restocking Until a Threshold

The "wait for a condition to change" pattern often looks like topping something up until it crosses a line. Consider a warehouse that restocks a product until it has at least 20 units on hand. Each restock adds a fixed amount:

The number of restocks isn't known in advance. It depends on the starting stock and the restock size. The loop figures it out by checking the condition each pass.

Infinite Loops and When They're Legitimate

An infinite loop is one whose condition never becomes false. The simplest form is while (true), where the condition is a literal true:

That sounds like a bug, and most of the time it is. But there are real cases where an infinite loop is the right shape:

  • A long-running process that handles work as it arrives, like a server waiting for incoming orders.
  • A retry pattern where you keep trying an action until it succeeds.
  • A menu-driven program that keeps showing options until the user picks "quit."

In every legitimate use, something inside the body breaks out of the loop. The exit happens with a break statement, a return from the surrounding method, or an exception. The shape, kept abstract:

The break statement here jumps out of the nearest enclosing loop. For now, the takeaway is that while (true) is fine when the body has a clear exit path. Without one, the result is an unintentional infinite loop, and that's a different story.

Common Bugs

The two most common while loop mistakes both come from sloppy bookkeeping around the condition variable. Both are easy to spot with practice.

Forgetting to Update the Condition Variable

What's wrong with this code?

The condition checks remainingStock, but the body never changes it. remainingStock stays at 3 forever, the condition stays true forever, and the program prints Selling unit. Stock: 3 until the process is killed.

Fix:

The fix is one line: remainingStock--; inside the body. Now each iteration reduces the value, the condition eventually fails, and the loop exits cleanly.

Run through this checklist for every while loop:

  • Does the condition refer to a variable?
  • Does the body change that variable?
  • Will that change eventually flip the condition to false?

A "no" to any of these signals an infinite loop.

Wrong Initialization

The other common bug is starting the loop with a value that either skips the body entirely or starts it in a broken state.

What's wrong with this code?

The author wanted the prompt to run at least once, but quantity starts at 1, so the condition quantity < 1 is already false. The loop body never runs.

Fix:

Initialize to a value that the condition rejects, not one it accepts. The general rule: a while loop's starting state and its exit state should be on opposite sides of the condition. For the body to run at least once, start outside the condition. For zero iterations to be a valid outcome (like draining an already-empty queue), the loop has to tolerate that.

Quiz

While Loop Quiz

10 quizzes