Namespaces
Variants
Actions

The while loop

From cppreference.com
< intro/control
Revision as of 23:30, 9 November 2013 by P12 (Talk | contribs)


The while loop is the simplest possible loop in C++. It repeatedly executes a specific set of statements block as long as the given condition is true.

The syntax of a while statement is as follows:

while(/*condition*/) {
    /*body*/
}

The code above works as follows:

1) /*condition*/ is checked.
a) If it returns true, the /*body*/ block runs. Return to (1).
b) Otherwise, execution continues after the closing bracket of the /*body*/ block.

This includes two special cases:

1) If the condition is already false before the loop begins, it never executes.
2) If the condition is true and this value never changes, the loop executes forever (endless loop). The programmer must ensure this never happens.

The example below prints the sequence of numbers from 0 to 10.

#include <iostream>
 
int main()
{
    int i = 0;
    while (i < 10) {
        std::cout << i << ' ';
        i = i + 1; // or ++i, which is equivalent
    }
    std::cout << '\n';
}

Output:

0 1 2 3 4 5 6 7 8 9

More on the syntax

/*condition*/ must be an expression that evaluates to true or false. Often, comparison operators ==, !=, <, <=, >, >= are used, e.g. like i != j. Also, the condition may be just a number: non-zero value is interpreted as true, wheres 0 will be interpreted as false.

/*body*/ must be one or more statements. If /*body*/ contains a single statement, the curly braces may be omitted, but this is not recommended practice as it may lead to bugs in the code.

The example below shows some more complex ways to use a while loop.

#include <iostream>
 
int main()
{
    int i = 10;
 
    // print a sequence 10..1
    while (i > 0) {
        std::cout << i << ' ';
        i--;
    }
    std::cout << '\n';
 
    // same as above, i is decremented before being printed
    while (i > 0) {
        i--;
        std::cout << i << ' ';
    }
    std::cout << '\n';
 
    // same as above, with i-- integrated into the condition
    i = 10;
    while (i-- > 0) { // check i > 0 and then decrement i
        std::cout << i << ' ';
    }
    std::cout << '\n';
 
    // the difference between --i and i--
    i = 10;
    while (--i > 0) { // decrement i and check i > 0
        std::cout << i << ' ';
    }
    std::cout << '\n';
 
    // Since i is going towards zero, we may just check
    // whether it is equal to zero
    i = 10;
    while (--i != 0) {
        std::cout << i << ' ';
    }
    std::cout << '\n';
}

Output:

10 9 8 7 6 5 4 3 2 1
9 8 7 6 5 4 3 2 1 0
9 8 7 6 5 4 3 2 1
9 8 7 6 5 4 3 2 1
9 8 7 6 5 4 3 2 1