Concept Flow - Do–while loop
Start
Execute body
Check condition
Exit
The do-while loop runs the code inside the loop first, then checks the condition. If true, it repeats; if false, it stops.
int i = 1; do { System.out.println(i); i++; } while (i <= 3);
| Step | i value | Condition (i <= 3) | Action | Output |
|---|---|---|---|---|
| 1 | 1 | true | Print 1, increment i to 2 | 1 |
| 2 | 2 | true | Print 2, increment i to 3 | 2 |
| 3 | 3 | true | Print 3, increment i to 4 | 3 |
| 4 | 4 | false | Exit loop |
| Variable | Start | After 1 | After 2 | After 3 | Final |
|---|---|---|---|---|---|
| i | 1 | 2 | 3 | 4 | 4 |
do-while loop syntax:
do {
// code
} while (condition);
Runs loop body first, then checks condition.
Repeats if condition true, stops if false.
Always runs at least once.What is the main difference between a do-while loop and a while loop in Java?
do-while loop behaviordo-while loop runs the code block first, then checks the condition to decide if it should repeat.while loopwhile loop checks the condition first before running the code block, so it may not run at all if the condition is false initially.do-while loop executes the code block at least once before checking the condition. -> Option Ado-while runs once before condition check [OK]Which of the following is the correct syntax for a do-while loop in Java?
?
do-while syntaxdo, then the code block in braces, followed by while (condition); with a semicolon.What will be the output of the following Java code?
int count = 1;
do {
System.out.print(count + " ");
count++;
} while (count <= 3);Identify the error in this do-while loop code snippet:
int i = 0;
do {
System.out.println(i);
i++
} while (i < 5);i++ is missing a semicolon at the end, which causes a syntax error.i++ -> Option DYou want to write a do-while loop that asks the user to enter a positive number and repeats until the user enters a positive number. Which code snippet correctly implements this?
Scanner sc = new Scanner(System.in);
int num;
do {
System.out.print("Enter a positive number: ");
num = sc.nextInt();
} while (???);num <= 0 ensures the loop repeats until the user enters a positive number.Pass the test and this pattern moves unknown