In C++, the do...while
loop is similar to the while
loop, but the code inside the loop is guaranteed to be executed at least once. The basic syntax of a do...while
loop in C++ is as follows:
do {
// code to be executed
} while (condition);
Here is an explanation of the parts of a do...while
loop:
- The code inside the loop is executed first, before the condition is checked.
- The
condition
is an expression that is evaluated after each iteration of the loop. If the condition is true, the loop continues to execute. If the condition is false, the loop terminates and the control passes to the next statement after the loop.
Here's an example of a do...while
loop in C++ that asks the user to enter a number between 1 and 10:
#include <iostream>
using namespace std;
int main() {
int num;
do {
cout << "Enter a number between 1 and 10: ";
cin >> num;
} while (num < 1 || num > 10);
cout << "You entered " << num << endl;
return 0;
}
In this example, the loop executes at least once, because the condition is checked after the user enters a number. If the number is less than 1 or greater than 10, the loop continues to execute and prompts the user to enter a new number. If the number is between 1 and 10, the loop terminates and the value of num
is printed.
Note that the condition in the do...while
loop is written with a semicolon at the end, unlike the while
and for
loops where the condition is written in parentheses.
Comments
Post a Comment