The do while loop in C++ is a looping statement that executes a block of code at least once before checking the condition. It is useful when the code must run one time regardless of the condition.
What is a do while Loop?
A do while loop is a control structure that:
- Executes the loop body first
- Checks the condition afterward
- Repeats the loop while the condition is true
Unlike the while loop, the condition is checked after execution.
Syntax of do while Loop
do {
// code to execute
} while (condition);
How do while Loop Works
- The loop body executes first
- The condition is checked
- If the condition is true, the loop repeats
- If false, the loop stops
Example of do while Loop
#include <iostream>
using namespace std;
int main() {
int i = 1;
do {
cout << i << endl;
i++;
} while (i <= 5);
return 0;
}
Output
1
2
3
4
5
Example: User Input Program
#include <iostream>
using namespace std;
int main() {
int number;
do {
cout << "Enter a number (0 to stop): ";
cin >> number;
cout << "You entered: " << number << endl;
} while (number != 0);
return 0;
}
Difference Between while and do while Loop
| while Loop | do while Loop |
|---|---|
| Condition checked first | Code executes first |
| May not execute at all | Executes at least once |
Example Showing Difference
#include <iostream>
using namespace std;
int main() {
int i = 10;
do {
cout << "Executed once";
} while (i < 5);
return 0;
}
Even though the condition is false, the loop runs once.
Infinite do while Loop
do {
cout << "Infinite Loop";
} while (true);
Use infinite loops carefully.
Why do while Loop is Important
The do while loop is important because it:
- Ensures code executes at least once
- Is useful for menu-driven programs
- Handles user input efficiently
- Simplifies repetitive tasks
- Supports condition-based repetition
Real-Life Example
Think of entering a password:
- You must enter it at least once
- The system checks if it is correct afterward
- If incorrect, it asks again
This is how a do while loop works.
Conclusion
The do while loop in C++ is a useful looping structure when code needs to execute at least once before checking a condition. It is commonly used in menus, input validation, and interactive applications.