for loop
Executes a loop.
Used as a more readable equivalent of while loop.
Contents |
[edit] Syntax
for ( init_expression ; cond_expression ; iteration_expression ) loop_statement | |||||||||
[edit] Explanation
The above syntax produces code equivalent to:
{
} |
|||||||||
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.
[edit] Keywords
[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 (int argc, char **argv) { unsigned i = 0, array [SIZE]; for( ; i < SIZE; ++i) array [i] = random() % 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