C++ While Loop

In C++, the while loop is a control flow statement that allows you to repeatedly execute a block of code as long as a specified condition is true. It is a pre-test loop, meaning that the condition is checked before the loop body is executed.

The syntax for the while loop in C++ is as follows:

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

Here, the condition is a boolean expression that evaluates to either true or false. If the condition is true, the code inside the loop is executed. After each iteration, the condition is evaluated again. If the condition is still true, the loop continues to execute. If the condition is false, the loop terminates, and the program continues with the next statement after the loop.

Let’s illustrate the while loop with an example. Consider a scenario where you want to print the numbers from 1 to 5:

#include 

int main() {
    int i = 1;
    while (i <= 5) {
        std::cout << i << " ";
        i++;
    }
    return 0;
}

In this example, we initialize a variable i with the value 1. The while loop then checks if i is less than or equal to 5. Since the condition is true, the code inside the loop is executed. The value of i is printed, followed by a space. We then increment i by 1 using the i++ statement.

After the first iteration, the value of i becomes 2, and the loop continues. This process repeats until i reaches 6. At that point, the condition i <= 5 becomes false, and the loop terminates.

The output of the above program will be:

1 2 3 4 5

As you can see, the while loop allows us to repeat a set of statements until a certain condition is met. It is important to ensure that the condition eventually becomes false to avoid an infinite loop.

The while loop can be used in various scenarios, such as reading input from a user until a specific condition is met, iterating over elements in an array, or performing calculations until a desired result is achieved.

It is worth noting that the while loop may not execute at all if the initial condition is false. In such cases, the code inside the loop will be skipped entirely.

In summary, the while loop in C++ provides a powerful mechanism for repeating a block of code based on a specified condition. By understanding its syntax and usage, you can effectively control the flow of your program and implement repetitive tasks with ease.

Scroll to Top