C++ while loop
A while loop is a type of loop that executes a block of code repeatedly until a condition is false. The condition is evaluated at the beginning of each iteration of the loop. If the condition is true, the loop body is executed. If the condition is false, the loop terminates.
The syntax for a while loop is as follows:
while (condition) {
// loop body
}
The condition can be any Boolean expression. If the condition evaluates to true, the loop body is executed. If the condition evaluates to false, the loop terminates.
Example
The following example shows a simple while loop:
int i = 0;
while (i < 10) {
std::cout << i << std::endl;
i++;
}
Output:
0
1
2
3
4
5
6
7
8
9
C++ do while loop
A do while loop is similar to a while loop, but it executes the loop body at least once before evaluating the condition. The condition is evaluated at the end of each iteration of the loop. If the condition is true, the loop body is executed again. If the condition is false, the loop terminates.
The syntax for a do while loop is as follows:
do {
// loop body
} while (condition);
Example
The following example shows a simple do while loop:
int i = 0;
do {
std::cout << i << std::endl;
i++;
} while (i < 10);
Output:
0
1
2
3
4
5
6
7
8
9
Difference between while loop and do while loop
The main difference between a while loop and a do while loop is that a do while loop executes the loop body at least once, even if the condition is false. A while loop, on the other hand, will not execute the loop body if the condition is false at the beginning of the first iteration.
Which type of loop you use depends on your specific needs. If you need to execute the loop body at least once, then you should use a do while loop. If you do not need to execute the loop body at least once, then you can use a while loop.