Concept Flow - Do–while loop
Start
Execute body
Check condition
Yes| No
Repeat
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 { cout << i << " "; i++; } while (i <= 3);
| Step | i value | Condition (i <= 3) | Action | Output |
|---|---|---|---|---|
| 1 | 1 | true | Print 1, i = i + 1 (i=2) | 1 |
| 2 | 2 | true | Print 2, i = i + 1 (i=3) | 2 |
| 3 | 3 | true | Print 3, i = i + 1 (i=4) | 3 |
| 4 | 4 | false | Exit loop |
| Variable | Start | After 1 | After 2 | After 3 | Final |
|---|---|---|---|---|---|
| i | 1 | 2 | 3 | 4 | 4 |
do {
// code to run
} while (condition);
- Runs loop body first, then checks condition.
- Repeats if condition true, stops if false.
- Executes at least once even if condition false initially.What is the main difference between a do-while loop and a while loop in C++?
do-while loop behaviordo-while loop executes the code block first, then checks the condition to decide if it repeats.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 runs 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 C++?
?
do-while syntaxdo { ... } while (condition); with braces and a semicolon after the while condition.What will be the output of the following C++ code?
int i = 3;
do {
std::cout << i << " ";
i--;
} while (i > 0);Identify the error in this do-while loop code snippet:
int x = 5;
do {
std::cout << x << " ";
x++;
} while x < 10;while must be enclosed in parentheses: while (x < 10);.x is valid; do is spelled correctly; loop ends with semicolon, which is correct.You want to write a do-while loop that asks the user to enter a positive number and repeats until the user enters a number greater than zero. Which code snippet correctly implements this?
?
num <= 0.do-while (num <= 0); which repeats until user enters positive number. int num = 0;
do {
std::cout << "Enter positive number: ";
std::cin >> num;
} while (num > 0); repeats while number is positive (wrong). int num;
while (num <= 0) {
std::cout << "Enter positive number: ";
std::cin >> num;
} uses while loop, not do-while. int num;
do {
std::cout << "Enter positive number: ";
std::cin >> num;
} while (num < 0); repeats while number is less than zero, so zero input stops loop incorrectly.Pass the test and this pattern moves unknown