C++ Control Statement Do-While Loop
The do-while loop is a control statement that executes a block of code repeatedly until a certain condition is met. Unlike other loops in C++, the do-while loop executes its code block at least once, regardless of the initial condition.
Syntax
The syntax of the do-while loop is as follows:
do {
//code to be executed
} while(condition);
The code block within the do
and while
statements is executed until the condition becomes false. The condition is evaluated after each iteration.
Example
Here is an example of a do-while loop in C++:
#include <iostream>
using namespace std;
int main() {
int i = 1;
do {
cout << i << " ";
i++;
} while(i <= 5);
return 0;
}
Output
The output of the above program will be:
1 2 3 4 5
Explanation
In the above example, the code block within the do-while loop will be executed until the value of i becomes greater than 5. The initial value of i is 1. After each iteration, the value of i is incremented by 1. The condition is checked after each iteration, and the loop will continue executing until the condition becomes false.
Use
The do-while loop is useful when you need to execute a block of code at least once, regardless of the initial condition. For example, when you need to prompt the user to enter a value and then validate that value.
Important Points
- The do-while loop always executes the code block at least once, unlike other loops in C++.
- The condition is evaluated after each iteration.
- It is important to make sure that the condition will eventually become false, or you may end up with an infinite loop.
Summary
The do-while loop is a control statement that executes a block of code repeatedly until a certain condition is met. It is useful when you need to execute a block of code at least once. The condition is evaluated after each iteration, and it is important to make sure the condition will eventually become false to avoid an infinite loop.