for loop

From cppreference.com
< c‎ | language

Executes a loop.

Used as a shorter equivalent of while loop.

Contents

[edit] Syntax

for ( init_expression ; cond_expression ; iteration_expression ) loop_statement

[edit] Explanation

Unless there are any continue statements, the above syntax produces code equivalent to:

{
init_expression ;
while ( cond_exression ) {
loop_statement
iteration_expression ;
}

}

The init_expression is executed before the execution of the loop. The cond_expression shall evaluate to value, convertible to bool. It is evaluated before each iteration of the loop. The loop continues only if its value is true. The loop_statement is executed on each iteration, after which iteration_expression is executed.

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. When there are continues in the loop body (loop_statement), then each continue passes control to the iteration_expression instead of passing to the next iteration. This way, at each iteration iteration_expression is guaranteed to be executed (unless we break out of the loop).

[edit] Keywords

for

[edit] Example

The following example demonstrates the usage of the for loop in an array manipulation

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

Output:

Array filled!
1 0 1 1 1 1 0 0