Structure and flow of control in a for loop

suggest change
for ([declaration-or-expression]; [expression2]; [expression3])
{
    /* body of the loop */
}

In a for loop, the loop condition has three expressions, all optional.

It can be either a declaration and initialization of a loop variable, or a general expression. If it is a declaration, the scope of the declared variable is restricted by the for statement.

Historical versions of C only allowed an expression, here, and the declaration of a loop variable had to be placed before the for.

Each instance of execution of the loop body is called an iteration.

Example:

for(int i = 0; i < 10 ; i++)
{
    printf("%d", i);
}

The output is:

0123456789

In the above example, first i = 0 is executed, initializing i. Then, the condition i < 10 is checked, which evaluates to be true. The control enters the body of the loop and the value of i is printed. Then, the control shifts to i++, updating the value of i from 0 to 1. Then, the condition is again checked, and the process continues. This goes on till the value of i becomes 10. Then, the condition i < 10 evaluates false, after which the control moves out of the loop.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents