do-while loop

From cppreference.com
< c‎ | language

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 <stdio.h>
#include <stdlib.h>
 
#define SIZE 8
 
int main(void)
{
    unsigned i = 0, array [SIZE];
 
    do
    {
        array [i] = rand() % 2;
        ++i;
    } while (i < SIZE);
 
    printf("Array filled!\n");
 
    i = 0;
    do
    {
        printf("%d ", array[i]);
        ++i;
    } while (i < SIZE);
 
    printf("\n");
 
    return EXIT_SUCCESS;
}

Output:

Array filled!
1 0 1 1 1 1 0 0