C++ Do-While Loop

The do-while loop in C++ is similar to the while loop but guarantees that the loop body will execute at least once. This is because the loop condition is evaluated after the loop body is executed. This makes the do-while loop particularly useful when you need to ensure that the loop's operations are performed at least a single time, regardless of the condition.

Syntax:

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

Condition: An expression that is evaluated after each iteration of the loop. If it evaluates to true, the loop continues; if false, the loop terminates.

Example:

#include <iostream>
using namespace std;

int main() {
    int i = 0;
    do {
        cout << "Iteration: " << i << endl;
        ++i;
    } while (i < 5);
    return 0;
}

Output:

Iteration: 0
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4

C++ Nested Do-While Loop

A nested do-while loop involves placing one do-while loop inside another. Similar to nested while loops, the inner loop executes fully for each iteration of the outer loop.

Example:

#include <iostream>
using namespace std;

int main() {
    int i = 0;
    do {
        int j = 0;
        do {
            cout << "(" << i << ", " << j << ") "
            ++j;
        } while (j < 3);
        cout << endl;
        ++i;
    } while (i < 2);
    return 0;
}

Output:

(0, 0) (0, 1) (0, 2)
(1, 0) (1, 1) (1, 2)

C++ Infinite Do-While Loop

An infinite do-while loop runs endlessly because the condition is always true. This can be useful for situations where you need continuous looping until an external event or condition breaks the loop.

Example:

#include <iostream>
using namespace std;

int main() {
    int count = 0;
    do {
        cout << "This loop will run forever." << endl;
        ++count;
    } while (true);
    return 0;
}