- What is a do-while loop?
- Syntax of do-while loop
- Important Notes:
- Flowchart of do-while loop
- Key Characteristics of do-while loop
- Example of do-while
- Program to print numbers from 1 to 5
- Step-by-Step Explanation:
- 1. Variable Initialization:
- 2. do Block:
- 3. while Condition:
- 🔢 Do-While Loop Execution:
- Real-Life Example of do while
- When to Use do-while vs. while
- Nested do-while Loops
- Example: Print 1 to 3, three times:
- Using break and continue in do-while
- Break – exits loop immediately:
- Continue – skips current iteration:
- Common Mistakes
- Test Your Knowledge
- Practice Questions
- Conclusion
- Challenge
In Java, loops are used to repeat a block of code multiple times until a certain condition is met. Among the different types of loops, the do-while loop is special because it executes the code block at least once, even if the condition is false.
In this tutorial you will learn everything about the do-while loop from scratch. By the end, you’ll be able to write and understand do-while loops confidently.
What is a do-while loop?
A do-while loop is a type of loop that always runs the code at least once, because it checks the condition after running the loop body.
It is called a post-tested loop because the condition is tested after execution.
Key Point: Even if the condition is false, the loop will still run one time.
Syntax of do-while loop
do {
// code to be executed
} while (condition);
Important Notes:
- The semicolon (
;) after thewhile(condition)is required. - The loop will keep executing as long as the condition is true.
- Code inside the block runs before the condition is checked.
Flowchart of do-while loop
+------------------+
| Execute block |
+------------------+
|
v
+------------------+
| Check condition |
+------------------+
|
+----+----+
| |
Yes No
| |
v x
Repeat Exit loop
Key Characteristics of do-while loop
| Feature | Description |
|---|---|
| Executes block at least once | Yes |
| Condition checked at… | After the block execution (post-test) |
| Ends with semicolon | Yes (while(condition);) |
| Useful for… | Menu-driven programs, input validation, etc. |
Example of do-while
Program to print numbers from 1 to 5
public class DoWhileExample {
public static void main(String[] args) {
int i = 1;
do {
System.out.println("Number: " + i);
i++;
} while (i <= 5);
}
}
Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Even if the condition was false initially, the first line would still execute.
Step-by-Step Explanation:
1. Variable Initialization:
int i = 1;
A variable i is declared and initialized with the value 1.
2. do Block:
do {
System.out.println("Number: " + i);
i++;
}
- The code inside the
doblock runs first, without checking the condition. - It prints the value of
i, then increasesiby 1 (i++).
3. while Condition:
while (i <= 5);
- After running the block once, it checks if
iis less than or equal to 5. - If true, it repeats the loop.
- If false, the loop stops.
🔢 Do-While Loop Execution:
| i value | Output | Condition after increment | Continue? |
|---|---|---|---|
| 1 | Number: 1 | 2 ≤ 5 → true | Yes |
| 2 | Number: 2 | 3 ≤ 5 → true | Yes |
| 3 | Number: 3 | 4 ≤ 5 → true | Yes |
| 4 | Number: 4 | 5 ≤ 5 → true | Yes |
| 5 | Number: 5 | 6 ≤ 5 → false | No |
Real-Life Example of do while
Think of brushing your teeth before checking your calendar.
You:
- Brush your teeth (task done once).
- Then check the calendar to see if it’s a working day (condition).
- If yes, repeat (e.g., get ready, pack bag, etc.).
Similarly, in a do-while, the task is always performed once before any condition check.
When to Use do-while vs. while
| Scenario | Use while | Use do-while |
|---|---|---|
| You want to test condition first | ✅ Yes | ❌ No |
| You want the block to execute at least once | ❌ No | ✅ Yes |
| Suitable for menu/input-driven programs | ❌ Sometimes | ✅ Perfect fit |
Nested do-while Loops
A nested do-while loop means placing one do-while loop inside another do-while loop. This structure is useful when you need to repeat a set of tasks multiple times within a bigger repeated process such as printing patterns or working with rows and columns.
The outer loop runs first and for each cycle of the outer loop, the inner loop runs completely. Even in a nested structure, each do-while loop ensures that its code block is executed at least once, regardless of the condition.
You can use one do-while loop inside another.
Example: Print 1 to 3, three times:
public class NestedDoWhile {
public static void main(String[] args) {
int i = 1;
do {
int j = 1;
do {
System.out.print(j + " ");
j++;
} while (j <= 3);
System.out.println();
i++;
} while (i <= 3);
}
}
Output:
1 2 3
1 2 3
1 2 3
Using break and continue in do-while
In a do-while loop, you can use break to immediately exit the loop when a certain condition is met. On the other hand, continue skips the remaining code in the current iteration and moves directly to the next loop cycle, after checking the condition again. These keywords help you control the flow of the loop based on specific logic or conditions.
Break – exits loop immediately:
int i = 1;
do {
if (i == 4) {
break;
}
System.out.println(i);
i++;
} while (i <= 5);
Output:
1 2 3
Continue – skips current iteration:
int i = 0;
do {
i++;
if (i == 3) {
continue;
}
System.out.println(i);
} while (i < 5);
Output:
1 2 4 5
(Note: 3 is skipped)
Common Mistakes
| Mistake | Correction |
|---|---|
Forgetting ; after while(condition) | Add semicolon like } while (condition); |
| Infinite loop due to no increment | Make sure to modify the loop variable |
| Misunderstanding: “It won’t run if condition is false” | Wrong – It runs once even if false |
Test Your Knowledge
Q1. What is the key difference between while and do-while?
Q2. How many times will the following code execute?
int x = 10;
do {
System.out.println("Run");
} while (x < 5);
Q3. Fill in the blank to print numbers 1 to 5:
int i = 1;
do {
System.out.println(i);
___;
} while(i <= 5);
Practice Questions
- Write a Java program using
do-whileto calculate the sum of numbers from 1 to 100. - Create a simple menu using
do-while:- Press 1 for Addition
- Press 2 for Subtraction
- Press 3 to Exit
- Use
do-whileto reverse a number entered by the user. - Create a program that keeps asking the user to enter a positive number, and stops only when a negative number is entered.
Conclusion
The do-while loop is a great concept when you want your code to run at least once before checking the condition. It’s especially useful in menu-driven applications, input validation, and games.
Challenge
Try writing a simple calculator that takes two numbers and a choice (1 for add, 2 for subtract, etc.) using a do-while loop. Exit when the user chooses 0.