C++ While Loop

In C++, a while loop is a control flow statement that allows you to repeatedly execute a block of code as long as a given condition is true. It is typically used to execute a certain section of code repeatedly until a certain condition is met.

Syntax

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

The condition is evaluated before each iteration of the loop. If the condition is true, the code inside the loop will be executed. If the condition is false, the loop will be terminated and the program will continue to execute the code that follows the loop.

Example

Here is an example of a simple while loop that counts from 1 to 10:

#include <iostream>

int main() {
    int i = 1;

    while (i <= 10) {
        std::cout << i << " ";
        i++;
    }
    std::cout << std::endl;

    return 0;
}

In this example, the loop will continue to execute as long as the variable i is less than or equal to 10. Each time the loop iterates, the value of i is incremented by 1 using the i++ operator. The result of this program will be the numbers 1 through 10 printed to the console.

Do-while loop

A do-while loop is similar to a while loop, but with a key difference: the code inside the loop is guaranteed to execute at least once, regardless of the condition.

#include <iostream>

int main() {
    int i = 1;

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

    return 0;
}

In the above example, the code inside the do-while loop will execute at least once, even if the condition i <= 10 is false on the first iteration. The result of this program will be the numbers 1 through 10 printed to the console, just like in the while loop example.

Infinite Loop

An infinite loop occurs when the condition in a while loop is always true. This can happen if the condition is not properly set or if the loop variable is not updated inside the loop. An infinite loop will cause the program to hang and can only be stopped by killing the program or by pressing the “break” button.

Conclusion

The while loop and do-while loop are powerful control flow statements that allow you to repeatedly execute a block of code as long as a certain condition is true. They are particularly useful for situations where you need to perform an action repeatedly until a specific goal is achieved. Remember to use them judiciously, as infinite loops can cause your program to crash.

Leave a Reply

Your email address will not be published. Required fields are marked *