Table of Contents
What is a Do-While Loop?
A do-while loop in Java is a control flow statement that executes a block of code first and then checks the condition at the end of each iteration. Because the condition is checked after the body executes, the loop body is guaranteed to run at least once — even if the condition is false from the very beginning. This is what makes the do-while loop fundamentally different from the for loop and the while loop, both of which check the condition before executing the body. The do-while loop is called an exit-controlled loop for this exact reason.
Syntax:
do {
// body of loop
} while (condition);
Example:
// Java program to implement
// do-while loop
public class TutorialforGeeks
{
public static void main(String[] args)
{
int i = 1;
do {
System.out.println("Iteration number: " + i);
i++;
} while (i = 5);
}
}
Output:
Explanation:Iteration number: 1
Iteration number: 2
Iteration number: 3
Iteration number: 4
Iteration number: 5
- The loop variable is declared and initialized int i =1 before the loop starts.
- The loop body executes first, it prints the current value of i and then increments it by 1.
- After the body executes, the condition i = 5 is checked.
- As long as the condition is true, the loop body runs again.
- When i becomes 6, the condition i = 5 becomes false and the loop exits.
- Even if i had been initialized to 6, the body would still have executed once before the condition was checked.
Key Features of Do-While Loop
- Exit-Controlled Loop: The do-while loop checks its condition after executing the loop body. This means no matter what the condition is, the body will always run at least once before any check takes place.
- Guaranteed First Execution: Unlike the for loop and while loop, the do-while loop guarantees that the loop body will execute at least one time. This makes it ideal for situations where an action must be taken before a decision is evaluated.
- Condition at the Bottom: The condition in a do-while loop is placed at the very end after the closing brace of the loop body. It is written as while (condition); and must always end with a semicolon.
- Best for Menu-Driven Programs: The do-while loop is the most natural choice for menu-driven programs where the menu must be displayed to the user at least once and then shown again based on the user's choice.
- No Built-in Update Expression: Like the while loop, the do-while loop does not have a built-in update expression. The programmer must manually update the loop variable inside the body to prevent the loop from running infinitely.
- Supports Break and Continue: The do-while loop fully supports the break statement to exit the loop immediately and the continue statement to skip the rest of the current iteration and jump directly to the condition check.
Basic Do-While Loop
The standard form where a counter variable controls how many times the loop runs.
Syntax:
int i = initialValue;
do {
// statements to execute
i++; // update expression
}
Example:
// Java program to implement
// do-while loop
public class TutorialforGeeks {
public static void main(String[] args)
{
System.out.println("Multiplication table of 7:");
int i = 1;
do {
System.out.println("7 x " + i + " = " + (7 * i));
i++;
} while (i = 10);
}
}
Output:
Multiplication table of 7:
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70
Explanation:
- int i = 1 is declared before the loop since do-while has no built-in initialization section.
- The loop body executes first, it prints the multiplication of 7 with i and then increments i.
- After the body, the condition i = 10 is checked.
- The loop continues as long as the condition is true.
- When i becomes 11, the condition fails and the loop stops cleanly after printing all 10 lines.
Do-While Loop with User Input
The most classic real-world use of a do-while loop, displaying a menu and repeating it based on the user's choice.
Syntax:
Scanner sc = new Scanner(System.in);
int choice;
do {
// display menu or prompt
// read user input
choice = sc.nextInt();
// process input
}
Example:
// Java program to implement
// do-while loop with user input
import java.util.Scanner;
public class TutorialforGeeks {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int choice;
do {
System.out.println("---- MENU ----");
System.out.println("1. Say Hello");
System.out.println("2. Say Goodbye");
System.out.println("3. Exit");
System.out.print("Enter your choice: ");
choice = sc.nextInt();
if (choice == 1) System.out.println("Hello!");
else if (choice == 2) System.out.println("Goodbye!");
else if (choice == 3) System.out.println("Exiting program.");
else System.out.println("Invalid choice. Try again.");
} while (choice != 3);
sc.close();
}
}
Output:
---- MENU ----
1. Say Hello
2. Say Goodbye
3. Exit
Enter your choice: 1
Hello!
---- MENU ----
1. Say Hello
2. Say Goodbye
3. Exit
Enter your choice: 3
Exiting program.
Explanation:
- The menu is displayed inside the do block, so it always appears at least once.
- The user enters a choice and the corresponding action is performed using if-else.
- After the body executes, the condition choice != 3 is checked.
- As long as the user does not enter 3, the menu is displayed again.
- When the user enters 3, the condition becomes false and the loop exits cleanly.
Infinite Do-While Loop
When the condition is always true, the loop runs forever until a break statement is encountered.
Syntax:
int count = 0;
do {
// statements to execute
count++;
if (count == limitValue) {
break; // exit the infinite loop
}
} while (true);
Example:
// Java program to implement infinite
// do-while loop
public class TutorialforGeeks{
public static void main(String[] args)
{
int count = 0;
do {
System.out.println("Count is: " + count);
count++;
if (count == 5) {
System.out.println("Limit reached. Exiting loop.");
break;
}
} while (true);
}
}
Output:
Count is: 0
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Limit reached. Exiting loop.
Explanation:
- do { } while (true) creates an infinite loop since the condition never becomes false on its own.
- Inside the loop, count is printed and then incremented after every iteration.
- When count reaches 5, a message is printed and break immediately exits the loop.
- Without the break statement, this loop would run forever and the program would never terminate.
Do-While Loop with Break and Continue
A do-while loop runs the code at least one time before checking the condition.
- break: The break statement stops the loop immediately.
- continue: The continue statement skips the remaining code of the current round and moves to the next check of the loop condition.
Syntax:
int i = 0;
do {
i++;
if (i == skipValue) {
continue; // skip current iteration
}
if (i == stopValue) {
break; // exit the loop completely
}
// statements to execute
} while (i limit);
Example:
// Java program to implement do-while loop
// with break and contibue statament
public class TutorialforGeeks {
public static void main(String[] args)
{
int i = 0;
do {
i++;
if (i == 3)
{
System.out.println("Skipping number: " + i);
continue;
}
if (i == 7)
{
System.out.println("Breaking at number: " + i);
break;
}
System.out.println("Current number: " + i);
} while (i 10);
}
}
Output:
Current number: 1
Current number: 2
Skipping number: 3
Current number: 4
Current number: 5
Current number: 6
Breaking at number: 7
Explanation:
- The loop starts with i = 0 and increments i at the very top of the body.
- When i == 3, the continue statement skips the print below and jumps to the condition check, so 3 is never printed as a current number.
- When i == 7, the break statement immediately exits the loop, so 7, 8, 9, and 10 are never printed.
- This example clearly demonstrates how break and continue provide fine-grained control inside a do-while loop.
Do-While Loop vs While Loop vs For Loop
| Feature | Do-While Loop | While Loop | For Loop |
|---|---|---|---|
| Pupose | Used when the loop body must execute at least once before the condition is checked. | Used when the loop should only run if the condition is true from the beginning. | Used when the number of iterations is fixed and known in advance. |
| Condition Check | The condition is checked after the body executes - an exit-controlled loop. |
The condition is checked before the body executes – an entry-controlled loop. | The condition is checked before the body executes - an entry-controlled loop |
| Minimum Executions | Body always executes at least once even if condition is false initially. | Body never executes if condition is false from the very beginning. | Body never executes if condition is false from the very beginning. |
| Best Used | Best used for menu-driven programs where the menu must show at least once. | Best used when iterations depend on a dynamic condition not known in advance. | Best used when the exact number of repetitions is known before the loop starts. |
| Update Expression | Must be written manually inside the loop body by the programmer. | Must be written manually inside the loop body by the programmer. | Built directly into the loop header alongside initialization and condition. |
| Example Use | Showing a menu to a user and repeating based on their choice. | Reading and validating user input until a correct value is entered. | Printing numbers from 1 to 100 or iterating over a fixed-size array. |
How Do-While Loop Works?
- Loop Body Executes: First Unlike every other loop in Java, the do-while loop runs its body first without checking any condition. This is what guarantees that the body always executes at least one time.
- Update the Variable: Inside the loop body, the variable that affects the condition must be updated. Without this, the condition will never change and the loop will become infinite.
- Condition is Checked: After the body finishes executing, the condition written in the while() part is evaluated. If it returns true, the loop goes back and runs the body again.
- Loop Repeats: As long as the condition remains true, the loop body keeps executing and the variable keeps getting updated after each iteration.
- Loop Exits: When the condition finally evaluates to false, the loop stops, and program execution continues with the next statement after the do-while block.
Conclusion
The do-while loop is a unique and powerful looping construct in Java that stands apart from all other loops because of one simple but important characteristic, it always executes its body at least once before checking the condition. This makes it the perfect tool for menu-driven programs, input validation scenarios, and any situation where an action must be taken before a decision is evaluated. While it may be used less frequently than the for loop and while loop in everyday programming, understanding the do-while loop gives you a complete picture of how loops work in Java. Knowing when to use each loop, for loop for fixed iterations, while loop for unknown iterations, and do-while loop for guaranteed first execution, makes you a more confident and capable Java programmer.
Frequently Asked Questions
1. Can a do-while loop execute zero times in Java?
2. Is the semicolon after while mandatory in a do-while loop?No, a do-while loop always executes its body at least once because the condition is checked only after the body has already run.
3. Can we use a do-while loop without any condition inside while?Yes, the semicolon after 'while (condition)' is mandatory in a do-while loop; missing it causes a compile-time error in Java.
4. Does the do-while loop work with String conditions?No, the while part of a do-while loop must always contain a valid boolean expression; leaving it empty causes a syntax error.
5. Can a do-while loop be converted into a while loop?No, the do-while loop condition must always be a boolean expression; strings are not accepted as conditions in Java.
Yes, a do-while loop can always be rewritten as a while loop, but you would need to manually execute the body once before the while loop to match the same behavior.
0 Comments