Namespaces
Variants
Actions

The do-while loop

From cppreference.com
< intro/control
Revision as of 23:55, 23 September 2013 by Corbin (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)


The do-while loop is closely related to the while loop, except it checks the continuation condition after execution of the loop body rather than before. Though while and for loops are much more common in practice than do-while loops, do-while loops are perfectly suited for tasks that must be executed at least once.

do {
    /* loop body */
} while (/*condition*/);

A do-while loop will execute the loop body and then check the loop condition. If the loop condition is true, the loop will repeat. If the condition is false, the loop is exited, and execution continues after the loop.

The below example illustrates the general flow of do-while loops along with it's special case of always executing at least once.

#include <iostream>
 
int main()
{
    std::cout << "x:";
 
    int x = 0;
    do {
        ++x;
        std::cout << " " << x;
    } while (x < 5);
 
    std::cout << "\n" << "y:";
 
    int y = 1729;
    do {
        ++y;
        std::cout << " " << y;
    } while (y < 5);
}

Output:

x: 1 2 3 4 5
y: 1730