C++ while loop

‮w//:sptth‬ww.theitroad.com

In C++, the while loop is a control structure that allows a block of code to be executed repeatedly as long as a specified condition is true. The syntax of the while loop is as follows:

while (condition) {
    // Code to execute for each iteration
}

The condition statement is checked before each iteration of the loop and is used to determine if the loop should continue or exit. The code block inside the while loop will be executed repeatedly as long as the condition is true.

Here's an example of a while loop:

int i = 0;
while (i < 5) {
    cout << i << endl;
    i++;
}

In this example, the loop initializes the variable i to 0, checks if i < 5, executes the code block (cout << i << endl; i++;), and then increments i by 1. This process is repeated until i >= 5, at which point the loop exits.

The while loop is useful when you don't know exactly how many times you need to execute a block of code, but you do know the condition that should be met in order to continue iterating. If you know exactly how many times the loop should execute, you may want to use a for loop instead.

You can also use a while loop to iterate over the elements of an array or container, like this:

int arr[] = {1, 2, 3, 4, 5};
int i = 0;
while (i < 5) {
    cout << arr[i] << endl;
    i++;
}

In this example, the loop iterates over the elements of the array arr, printing each element to the console.