C for Loop
The for loop allows you to write a loop control structure that executes a specified number of times.
Syntax
The syntax of a for loop in C language:
for ( init; condition; increment )
{
statement(s);
}
Here is the control flow of the for loop:
init is executed first and only once. This step allows you to declare and initialize any loop control variables. You can also leave this empty, as long as a semicolon appears.
Next, the condition is evaluated. If it is true, the loop body is executed. If it is false, the loop body is not executed and control flow jumps to the next statement following the for loop.
After executing the loop body, control flow jumps back to the increment statement. This statement allows you to update the loop control variable. This statement can also be left empty, as long as a semicolon appears after the condition.
The condition is evaluated again. If it is true, the loop executes and this process repeats (loop body, then increment, then re-evaluate the condition). When the condition becomes false, the for loop terminates.
Flowchart
Example
Example
#include <stdio.h>
int main ()
{
/* for loop execution */
for( int a = 10; a < 20; a = a + 1 )
{
printf("value of a: %d\n", a);
}
return 0;
}
When the above code is compiled and executed, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19