Do While Loop
The do-while
Loop in C++:
The do-while
loop in C++ is similar to the while
loop, but with a key difference: the do-while
loop guarantees that the loop body is executed at least once, even if the condition is initially false. The syntax of a do-while
loop is as follows:
do {
// Code to be executed
} while (condition);
Here's an example of a simple do-while
loop that prints the numbers from 1 to 5:
#include <iostream>
int main() {
int i = 1;
do {
std::cout << i << " ";
++i; // Increment the loop control variable
} while (i <= 5);
return 0;
}
In this example, the loop will print the numbers 1 to 5, just like the while
loop. The key difference is that the condition i <= 5
is checked after the first execution of the loop body, ensuring that the loop body is executed at least once.
The output of this program will be:
1 2 3 4 5
Here's another example that demonstrates the use of do-while
in a menu-driven program:
#include <iostream>
int main() {
char choice;
do {
std::cout << "1. Print Hello\n";
std::cout << "2. Print Goodbye\n";
std::cout << "3. Exit\n";
std::cout << "Enter your choice: ";
std::cin >> choice;
switch (choice) {
case '1':
std::cout << "Hello!\n";
break;
case '2':
std::cout << "Goodbye!\n";
break;
case '3':
std::cout << "Exiting the program.\n";
break;
default:
std::cout << "Invalid choice. Please try again.\n";
}
} while (choice != '3');
return 0;
}
In this example, the menu is displayed, and the user is prompted to enter a choice. The loop continues to display the menu and process choices until the user chooses to exit by entering '3'.
Use do-while
when you want to ensure that a certain block of code is executed at least once, regardless of the initial condition.