Do-While Loop in Java | Control Flow in Java
The do-while loop in Java is a control flow statement that allows code to be executed repeatedly based on a boolean condition, but it guarantees that the loop's body will be executed at least once. This makes it useful for scenarios where you want to ensure at least one iteration occurs.
Key Points on Do-While Loop:
- The do-while loop checks the condition after executing the loop body.
- It’s suitable when the loop needs to execute at least once, regardless of the condition.
- Make sure to modify the loop variable within the loop to avoid infinite loops.
- The loop will execute one or more times based on the condition.
- It can be combined with control statements like break and continue.
Syntax of Do-While Loop:
Syntax Example
do {
// Code to execute in each iteration
} while (condition);
Example of Do-While Loop in Java:
This example demonstrates a basic do-while loop that prints numbers from 1 to 5.
Code Example 1
public class PrintNumbersDoWhile {
public static void main(String[] args) {
int i = 1;
do {
System.out.println(i);
i++; // Increment the loop variable
} while (i <= 5);
}
}
Output for Code Example 1:
1
2
3
4
5
2
3
4
5
Using Control Statements:
This example shows how to use the break statement in a do-while loop.
Code Example 2
public class BreakDoWhileExample {
public static void main(String[] args) {
int i = 1;
do {
if (i == 5) {
break; // Exit the loop when i equals 5
}
System.out.println(i);
i++;
} while (i <= 10);
}
}
Output for Code Example 2:
1
2
3
4
2
3
4
Example of a Do-While Loop with Condition Change:
This example uses a do-while loop to sum numbers until a certain limit is reached.
Code Example 3
public class SumDoWhileExample {
public static void main(String[] args) {
int sum = 0;
int i = 1;
do {
sum += i; // Add i to sum
i++; // Increment i
} while (i <= 5);
System.out.println("Sum: " + sum);
}
}
Output for Code Example 3:
Sum: 15
Detailed Explanation:
- Execution Order: The loop's body is executed once before the condition is checked.
- Condition: The loop continues as long as this condition is true. If false, the loop exits.
- Increment/Decrement: Ensure that the loop variable is modified within the loop to avoid infinite loops.
- Control Statements: Use break to exit the loop early and continue to skip to the next iteration.
By mastering the do-while loop, developers can ensure that certain code runs at least once while still maintaining control over the flow of their Java programs.