01 / 21

While & Do-While
Loops in Java

Master condition-controlled repetition with while and do-while loops: when to use each, how they execute, and how to avoid common pitfalls.

Java Control Flow

What Is a Loop?

A loop is a control structure that repeats a block of code as long as a specified condition remains true. Instead of writing the same instruction ten times, you write it once and let the loop handle the repetition.

Efficiency
Eliminates redundant code by repeating logic automatically.
Flexibility
The number of iterations can depend on user input or data at runtime.

The while Loop

A while loop checks its condition before each iteration. If the condition is false from the start, the body never executes.

while (condition) {
  // body: runs while condition is true
}
Start condition true? true body false End

The do-while Loop

A do-while loop checks its condition after each iteration. The body always executes at least once, regardless of the condition.

do {
  // body: runs at least once
} while (condition);
Start body condition true? true false End

Syntax of the while Loop

int count = 1;

while (count <= 5) {
  System.out.println("Count: " + count);
  count++;
}
1
Initialize the loop variable before the loop.
2
Test the boolean condition at the top of each iteration.
3
Update the loop variable inside the body to avoid an infinite loop.

Syntax of the do-while Loop

Scanner scanner = new Scanner(System.in);
int num;

do {
  System.out.println("Enter a positive number:");
  num = scanner.nextInt();
} while (num <= 0);

while vs do-while

while do-while
Condition check Before the body After the body
Minimum executions 0 1
When to use May not need to run at all Must run at least once
Typical use case Reading until end of file Menu prompts, input validation
Trailing semicolon No Yes (required)

When to Use Each Loop

while
Sentinel-controlled loops: reading input until a marker value. Search loops: scanning an array until a match is found or the end is reached.
do-while
Input validation: prompt the user, then check if the input is valid. Menu-driven programs: show choices at least once before checking the exit option.

Step-by-Step Approach

1
Identify the repetition: what action needs to repeat?
2
Define the condition: what boolean expression controls continuation?
3
Choose the loop type: must the body run at least once? Use do-while. Otherwise, while.
4
Initialize variables before the loop (counter, accumulator, sentinel).
5
Update state inside the body so the condition eventually becomes false.
6
Trace the loop on paper: verify that it terminates and produces the correct output.

Example 1: Sum of 1 to N

Compute the sum \( 1 + 2 + \ldots + n \) using a while loop.

int n = 5, i = 1, sum = 0;

while (i <= n) {
  sum += i;
  i++;
}

System.out.println("Sum = " + sum);
// Output: Sum = 15

Example 2: Input Validation

Force the user to enter a number between 1 and 100 using do-while.

Scanner scanner = new Scanner(System.in);
int grade;

do {
  System.out.print("Enter grade (1-100): ");
  grade = scanner.nextInt();
} while (grade < 1 || grade > 100);

System.out.println("Valid: " + grade);

Example 3: Sentinel-Controlled Loop

Compute the average of user-entered numbers. Stop when the user enters -1.

Scanner scanner = new Scanner(System.in);
int num = 0, count = 0, sum = 0;

System.out.print("Enter number (-1 to stop): ");
num = scanner.nextInt();

while (num != -1) {
  sum += num;
  count++;
  System.out.print("Next (-1 to stop): ");
  num = scanner.nextInt();
}

if (count > 0)
  System.out.println("Avg: " + (double)sum / count);

Infinite Loops

An infinite loop occurs when the loop condition never becomes false. The program runs forever (or until you force-quit it).

// Bug: count is never updated!
int count = 1;
while (count <= 5) {
  System.out.println(count);
  // Missing: count++;
}

Tracing a while Loop

What does this code print?

int x = 10;
while (x > 1) {
  x = x / 2;
  System.out.print(x + " ");
}
Iteration x before x / 2 Output
11055
2522
3211
41\(x > 1\) is false: exit

Common Mistakes

✕ Off-by-one error
Using < instead of <=, causing one too few or one too many iterations.
✕ Missing update
Forgetting to modify the loop variable inside the body, creating an infinite loop.
✕ Forgetting semicolon
Omitting the ; after the do-while condition causes a compilation error.
✕ Accidental semicolon
Placing ; after while(condition); creates an empty while body: the real body runs only once.
✕ Wrong loop type
Using while for input validation skips the prompt entirely when the variable is uninitialized or already valid.

Summary Comparison

Feature while do-while for
Condition positionTop (pre-test)Bottom (post-test)Top (pre-test)
Min iterations010
Best forUnknown countAt-least-onceKnown count
Init locationBefore loopBefore loopIn header
Update locationIn bodyIn bodyIn header
Semicolon after )NoYesNo

Question 1 of 5

What is the minimum number of times a do-while loop body executes?

Question 2 of 5

What does this code print?

int x = 0;
while (x > 0) {
  System.out.print(x + " ");
  x--;
}
System.out.print("done");

Question 3 of 5

You need to prompt a user for a password and keep asking until they enter the correct one. Which loop type is most appropriate?

Question 4 of 5

What is the value of sum after this code runs?

int sum = 0, i = 1;
while (i < 4) {
  sum += i;
  i++;
}

Question 5 of 5

Which of the following causes an infinite loop?