C++ Do-While

Difference between 'while' & 'do-while' loop.

Do-While Loop:

The 'do-while' loop is similar to the 'while' loop, but with a key difference: the 'do-while' loop guarantees that the loop's body is executed at least once, regardless of whether the loop condition is initially true or false.

Here's the basic syntax of a 'do-while' loop:

do {
    // code to be executed
} while (condition);

Breakdown:

1. The 'condition' is evaluated before the execution of the loop body. If the condition is true, the code inside the loop is executed. If the condition is false initially, the loop is skipped, and the program continues with the next statement after the loop.

2. After executing the loop body, the program goes back to the beginning of the loop (the 'while' statement) and checks the condition again.

3. If the condition is still true, the loop body is executed again. This process repeats until the condition becomes false. Once the condition is false, the program exits the loop, and execution continues with the next statement after the loop.

Here's a example of a do-while loop that prints numbers from 1 to 5:

cpp Copy Code
#include<iostream>

int main() {
    int i = 1;

    do {
        std::cout << i << " ";
        i++; // increment the counter variable
    } while (i <= 5);

    return 0;
}

Explanation:

the loop body is executed at least once because the condition is checked after the loop body. The loop will continue executing as long as the condition 'i <= 5' is true.

Output:
1 2 3 4 5

Note: Just like with the 'while' loop, it's crucial to ensure that the loop condition eventually becomes false to avoid an infinite loop.

What's Next?

We actively create content for our YouTube channel and consistently upload or share knowledge on the web platform.