C++ Do-While Loop: Usage and Examples

In C++, the do while statement is a type of loop statement where the loop body is executed first, and then the loop condition is checked to see if it is true. The basic syntax is as follows:

do {
    // 循环体
} while (条件);

The execution process of the do-while statement involves first executing the loop body once, then checking if the condition is true. If the condition is true, the loop body continues to be executed until the condition becomes false, at which point the loop stops.

The key difference between the while statement and the do while statement is that the do while statement guarantees that the loop body will be executed at least once, whereas the while statement may not execute the loop body at all if the condition is false.

Here is a simple example demonstrating the usage of the do while statement:

#include <iostream>

int main() {
    int i = 0;

    do {
        std::cout << i << " ";
        i++;
    } while (i < 5);

    return 0;
}

The code above will output: 0 1 2 3 4

In this example, the loop will execute at least once and will stop when the value of i is greater than or equal to 5.

bannerAds