C++ While Loop

The while loop in C++ is used for repeating a block of code as long as a specified condition remains true. Unlike the for loop, the while loop is ideal for situations where the number of iterations is not known in advance, and the loop continues to execute as long as the condition is met.

Syntax:

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

Condition: An expression that is evaluated before each iteration. If it evaluates to true, the loop body executes. If false, the loop terminates.

Example:

#include <iostream>
using namespace std;

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

    return 0;
}

Output:

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

C++ Nested While Loop

A nested while loop involves placing one while loop inside another. The inner loop executes completely for each iteration of the outer loop. This can be useful for scenarios requiring multi-dimensional iteration or complex looping structures.

Example:

#include <iostream>
using namespace std;

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

    return 0;
}

Output:

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

C++ Infinite While Loop

An infinite while loop runs endlessly because the condition is always true. This can be useful for situations where you need a loop to run indefinitely until an external condition or event breaks the loop.

Example:

#include <iostream>
using namespace std;

int main() {
    while (true) {
        cout << "This loop will run forever." << endl;

    }
    return 0;
}

Output:

This loop will run forever.