Understanding the Do-While Loop in C++
C++ | Tips
In C++, loops are indispensable for executing code repeatedly, and one unique structure in this family is the do-while
loop. Unlike other loops, do-while
guarantees the loop executes at least once before it evaluates the condition. In this post, we’ll explore the mechanics, syntax, and practical use cases of the do-while
loop using illustrative examples in C++.
C++ Tutorials GitHub repo:
Video Tutorial :
Basics of the Do-While
Loop
Syntax
The do-while
loop starts with the do
keyword, followed by the block of code to be executed. After the block, the while
condition is written and checked after each iteration.
do {
// Code block
} while (condition);
The key difference here is that the code in the do
block runs first and only then does the loop check the condition
to determine if it should continue.
Simple Example
Let’s take a look at a basic do-while
loop that increments a variable until it reaches a specified value.
#include <iostream>
int main() {
int number {0};
do {
number++;
std::cout << "Number: " << number << std::endl;
} while (number < 5);
std::cout << "Final number: " << number << std::endl;
return 0;
}
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Final number: 5
Explanation
- The loop initializes
number
to 0. - Inside the
do
block,number
is incremented by 1 and printed. - After each iteration, the condition
(number < 5)
is checked. Iftrue
, the loop runs again. - Once
number
reaches 5, the condition fails, and the loop exits.
Notice that even if number
were initially greater than 5, the loop would still execute once before evaluating the condition.
When to Use a Do-While
Loop
The do-while
loop shines when you need the code to execute at least once regardless of conditions. Here are some practical scenarios:
- User input validation: You can use
do-while
to prompt users to enter data until valid input is received. - Menu navigation: Useful for displaying menus where users select options and choose to repeat the menu until they exit.
- Repeated calculations: Where you need to calculate a value or call a function at least once before checking conditions.
Advanced Example: Menu Selection
Let’s use a do-while
loop to create a simple menu for user selection.
#include <iostream>
int main() {
int choice;
do {
std::cout << "\nMenu Options:\n";
std::cout << "1. Option A\n";
std::cout << "2. Option B\n";
std::cout << "3. Option C\n";
std::cout << "0. Exit\n";
std::cout << "Select an option: ";
std::cin >> choice;
switch (choice) {
case 1:
std::cout << "You selected Option A.\n";
break;
case 2:
std::cout << "You selected Option B.\n";
break;
case 3:
std::cout << "You selected Option C.\n";
break;
case 0:
std::cout << "Exiting menu.\n";
break;
default:
std::cout << "Invalid option. Try again.\n";
}
} while (choice != 0);
return 0;
}
Menu Options:
1. Option A
2. Option B
3. Option C
0. Exit
Select an option: 2
You selected Option B.
Menu Options:
1. Option A
2. Option B
3. Option C
0. Exit
Select an option: 0
Exiting menu.
In this example, the menu displays at least once. After each selection, the do-while
loop condition checks if choice
is 0 (to exit) or repeats the menu otherwise. This is ideal for menus where options need to repeat until a user chooses to exit.
Key Differences: Do-While
vs While
While loops check the condition first, meaning they can potentially skip execution entirely if the condition is false from the start. In contrast, a do-while
loop will execute at least once. Here’s a simple side-by-side comparison:
// While loop
int count = 0;
while (count > 0) {
std::cout << "This will not print because count > 0 is false initially." << std::endl;
}
// Do-while loop
do {
std::cout << "This will print at least once." << std::endl;
} while (count > 0);
In cases where an initial action is needed, the do-while
loop can be much more concise and intentional.
Conclusion
The do-while
loop in C++ is a handy control structure that guarantees at least one execution of a code block. It’s useful for menus, user input validation, and situations where an initial action is required before condition checking. By mastering both while
and do-while
loops, you can make your C++ programs more flexible and responsive to specific requirements.