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.
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.
The while Loop
A while loop checks its condition before each iteration. If the condition is false from the start, the body never executes.
// body: runs while condition is true
}
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.
// body: runs at least once
} while (condition);
Syntax of the while Loop
while (count <= 5) {
System.out.println("Count: " + count);
count++;
}
Syntax of the do-while Loop
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
Step-by-Step Approach
Example 1: Sum of 1 to N
Compute the sum \( 1 + 2 + \ldots + n \) using a while loop.
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.
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.
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).
int count = 1;
while (count <= 5) {
System.out.println(count);
// Missing: count++;
}
Tracing a while Loop
What does this code print?
while (x > 1) {
x = x / 2;
System.out.print(x + " ");
}
| Iteration | x before | x / 2 | Output |
|---|---|---|---|
| 1 | 10 | 5 | 5 |
| 2 | 5 | 2 | 2 |
| 3 | 2 | 1 | 1 |
| 4 | 1 | \(x > 1\) is false: exit | |
Common Mistakes
Summary Comparison
| Feature | while | do-while | for |
|---|---|---|---|
| Condition position | Top (pre-test) | Bottom (post-test) | Top (pre-test) |
| Min iterations | 0 | 1 | 0 |
| Best for | Unknown count | At-least-once | Known count |
| Init location | Before loop | Before loop | In header |
| Update location | In body | In body | In header |
| Semicolon after ) | No | Yes | No |
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?
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?
while (i < 4) {
sum += i;
i++;
}
Question 5 of 5
Which of the following causes an infinite loop?