C Language Iteration Statements/Loops: for, while, do-while Structure and flow of control in a for loop


Example

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

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

  • The first expression, declaration-or-expression, initializes the loop. It is executed exactly once at the beginning of the loop.
C99

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.

C99

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

  • The second expression, expression2, is the test condition. It is first executed after the initialization. If the condition is true, then the control enters the body of the loop. If not, it shifts to outside the body of the loop at the end of the loop. Subsequently, this conditon is checked after each execution of the body as well as the update statement. When true, the control moves back to the beginning of the body of the loop. The condition is usually intended to be a check on the number of times the body of the loop executes. This is the primary way of exiting a loop, the other way being using jump statements.
  • The third expression, expression3, is the update statement. It is executed after each execution of the body of the loop. It is often used to increment a variable keeping count of the number of times the loop body has executed, and this variable is called an iterator.

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

Example:

C99
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.