Topic 17 of 83
Do-While Loop
Overview
The do-while loop is a variant of the while loop that evaluates its condition at the end of the block. This guarantees the loop body executes *at least once*.
Syntax
cpp
int i = 0;
do {
cout << "This prints at least once.";
i++;
} while (i < 0); // Condition is false, but loop ran once.Common Pitfalls
- Forgetting the semicolon `;` after the `while(condition)` statement. It is required in a do-while loop.
Interview Tips
- Know that the classic use case for a do-while loop is prompting a user for input and validating it.
Real-World Example
Prompting user for valid input.
example
cpp
#include <iostream>
using namespace std;
int main() {
int choice;
do {
cout << "Enter a positive number: ";
cin >> choice;
} while (choice <= 0);
cout << "You entered: " << choice << endl;
return 0;
}