Comprehensive guide to C++ looping structures — while, do-while, and for loops — with clear syntax, annotated examples, menu-driven program patterns, and practical tips for beginners.
What is a do-while loop?
A do-while loop executes the code at least once, then checks the condition.
do {
// code to execute
} while (condition);
👉 Key point: The condition is checked after the loop body.
#include <iostream>
using namespace std;
int main() {
int i = 1;
do {
cout << i << " ";
i++;
} while (i <= 5);
return 0;
}
Output
1 2 3 4 5
Explanation:
i starts at 1i increases by 1i becomes greater than 5#include <iostream>
using namespace std;
int main() {
int count = 1;
do {
cout << "Hello\n";
count++;
} while (count <= 3);
return 0;
}
Explanation:
#include <iostream>
using namespace std;
int main() {
int i = 1, sum = 0;
do {
sum += i;
i++;
} while (i <= 5);
cout << "Sum = " << sum;
return 0;
}
Output
Sum = 15
#include <iostream>
using namespace std;
int main() {
int choice;
do {
cout << "\n1. Say Hello";
cout << "\n2. Say Bye";
cout << "\n3. Exit";
cout << "\nEnter your choice: ";
cin >> choice;
if (choice == 1)
cout << "Hello!\n";
else if (choice == 2)
cout << "Bye!\n";
} while (choice != 3);
return 0;
}
Why do-while here?
#include <iostream>
using namespace std;
int main() {
int i = 10;
do {
cout << "This will print once\n";
} while (i < 5);
return 0;
}
Explanation:
while loopwhile vs do-while| Feature | while | do-while |
|---|---|---|
| Condition checked | Before loop | After loop |
| Runs at least once | ❌ No | ✅ Yes |
| Best for | Unknown executions | Menus / user input |
do-while✅ When the loop must execute at least once ✅ For menus, password checks, user input