Control Flow & Loops

The while & do-while Loops

15 min Lesson 5 of 14

The while & do-while Loops

The for loop is ideal when you know in advance how many iterations you need. But what if you do not know the count — what if you want to keep asking a user for input until they type a valid number, or keep reading records until the data runs out? That is where the while and do-while loops shine.

The while Loop — Entry-Controlled

A while loop checks its condition before each iteration. If the condition is false right from the start, the body never runs at all.

int count = 1; while (count <= 5) { System.out.println("count = " + count); count++; } // Output: count = 1 count = 2 count = 3 count = 4 count = 5

The structure has three parts you must manage yourself:

  1. Initialise the variable before the loop (int count = 1).
  2. Test the condition at the top of each iteration.
  3. Update the variable inside the body so the condition eventually becomes false.
Forgetting the update step causes an infinite loop. If count++ were missing in the example above, the condition count <= 5 would stay true forever and your program would hang. Always verify that your loop body moves toward the exit condition.

Sentinel Values

A sentinel value is a special input the user types (or a special data value your program encounters) that signals "stop the loop." This is one of the most practical uses of while.

import java.util.Scanner; public class SentinelDemo { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int sum = 0; System.out.println("Enter numbers to sum. Type -1 to stop."); int input = scanner.nextInt(); // read first value before the loop while (input != -1) { // -1 is the sentinel sum += input; input = scanner.nextInt(); // read next value at end of body } System.out.println("Total: " + sum); scanner.close(); } }
Read before the loop, read again at the end of the body. This "priming read" pattern ensures the condition is always tested with a freshly read value. It is the standard idiom for sentinel-controlled while loops.

The do-while Loop — Exit-Controlled

A do-while loop places the condition after the body. This guarantees the body executes at least once, even if the condition is immediately false.

import java.util.Scanner; public class DoWhileDemo { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int number; do { System.out.print("Enter a positive number: "); number = scanner.nextInt(); } while (number <= 0); // keep asking until input is valid System.out.println("You entered: " + number); scanner.close(); } }

Without do-while you would have to either duplicate the prompt before the loop or use a workaround. The exit-controlled design is a natural fit whenever the body must run once to produce the value that the condition checks.

while vs do-while — When to Use Each

  • Use while when the loop might not need to run at all (e.g., process a file that could be empty).
  • Use do-while when the loop body must always run at least once (e.g., show a menu before checking the user's choice).

Avoiding Infinite Loops

Every loop needs a guaranteed exit path. Ask yourself three questions before you write any while loop:

  1. What variable or condition controls the loop?
  2. Is that variable modified inside the body?
  3. Will the modification eventually make the condition false?
// DANGER — infinite loop: condition never changes boolean running = true; while (running) { System.out.println("This never stops!"); // running is never set to false } // FIXED — loop exits when the user types "quit" import java.util.Scanner; Scanner sc = new Scanner(System.in); String command = ""; while (!command.equals("quit")) { System.out.print("Command: "); command = sc.nextLine(); System.out.println("You typed: " + command); }
During development, if you accidentally trigger an infinite loop, press Ctrl + C in your terminal to force-stop the program. In an IDE, click the red Stop button. Add a print statement inside the loop body as a quick sanity check while debugging.

Summary

The while loop is entry-controlled: the condition is checked first and the body may never execute. The do-while loop is exit-controlled: the body always runs at least once. Sentinel values give while loops a clean, user-driven exit condition. Always ensure your loop body moves toward the exit condition to prevent infinite loops.