Cover Image for C++ Do-While Loop
64 views

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:

C++
do {
    // Code to be executed
} while (condition);

Here’s an example of a do-while loop:

C++
#include <iostream>

int main() {
    int i = 1;

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

    std::cout << std::endl;

    return 0;
}

Output:

Plaintext
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 of i 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 is true, the loop continues; if it’s false, 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.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS