C++ Do-While Loop
The C++ do-while
loop is a control structure used for repetitive execution of a block of code. It is similar to the while
loop, but with one key difference: the do-while
loop always executes the block of code at least once before checking the loop condition. This guarantees that the code inside the loop will run at least once.
The basic syntax of the do-while
loop is as follows:
do {
// Code to be executed
} while (condition);
Here’s an example of a do-while
loop:
#include <iostream>
int main() {
int i = 1;
do {
std::cout << i << " ";
i++;
} while (i <= 5);
std::cout << std::endl;
return 0;
}
Output:
1 2 3 4 5
In this example:
- The loop begins with the
do
keyword, followed by a block of code enclosed in curly braces. In this case, it prints the value ofi
and increments it. - After the block of code, there is a
while
keyword followed by a condition in parentheses. This condition is evaluated after the block of code is executed. If the condition istrue
, the loop continues; if it’sfalse
, the loop terminates.
It’s important to note that the code inside the do-while
loop is guaranteed to run at least once because the condition is checked after the first iteration. If the condition is false
initially, the loop will execute once before exiting.
do-while
loops are useful when you need to ensure that a certain block of code runs at least once, regardless of the condition, and then continue executing based on the condition.