1.4.3 While Loops

Basic while loops are the same as Java:

while (boolean expression)
{
    // Will execute if boolean is true, and until 
    // the boolean expression is false
}

A while loop executes if the boolean expression at the start evaluates to true. Once in the block of code, the loop doesnโ€™t get evaluated again until it finishes executing the code. This means that even if the expression evaluates to false part way through the block of code, the block will continue until it reaches the end.

Loop and a half

Many times, you may find the need to assess the state of a variable part way through a loop. For example, if you ask a user for a number between 1 and 10, you need to ask them for a value before starting the loop, and then inside the loop after they enter a new value.

One way to get around this is to use the loop and a half set up. With a loop and a half, you set your boolean expression to true. This creates an infinite loop, but you can break out of the loop using a break command.

int sum = 0;
while (true) {
    cout << "Please enter a number(0 to quit): ";
    int num;
    cin >> num;
    if (num == 0) break;
    sum += num;
}

Notice in this example how the infinite loop is broken when the user enter 0. This breaks the cycle before the number is added to the next number.

Try This Example

Last updated