do-while loop

From Cppreference

Jump to: navigation, search

Executes a loop.

Used where code needs to be executed several times while some condition is present. the code is executed at least once.

Contents

[edit] Syntax

do loop_statement while ( cond_expression )

[edit] Explanation

cond_expression shall be an expression, whose result is convertible to bool. It is evaluated after each execution of loop_statement. The loop continues execution only if the cond_expression evaluates to true.

If the execution of the loop needs to be terminated at some point, break statement can be used as terminating statement.

If the execution of the loop needs to be continued at the end of the loop body, continue statement can be used as shortcut.

[edit] Keywords

do, while

[edit] Example

#include <iostream>
 
int main()
{
    int i = 0;
    do i++;
    while (i < 10);
 
    std::cout << i << '\n';
 
    i = 11;
    do i = i + 10;
    while (i < 10); //the code is executed even if the condition is false before the loop
 
    std::cout << i << '\n';
 
    int j = 2;
    do {
        j += 2;
        std::cout << j << " ";
    } while (j < 9);
    }

Output:

10
21
4 6 8 10