C for Loop
forLoops allow you to write a loop control structure that executes a specified number of times.
Syntax
In C languageforThe syntax of the loop:
for ( init; condition; increment )
{
statement(s);
}
Below is the control flow of the for loop:
- initIt is executed first, and only once. This step allows you to declare and initialize any loop control variables. You can also write no statement here, as long as a semicolon appears.
- Next, it will evaluateconditionIf true, the loop body is executed. If false, the loop body is not executed, and control flow jumps to the next statement immediately following the for loop.
- After executing the for loop body, control flow jumps back to the above statement.incrementStatement. This statement allows you to update the loop control variable. This statement can be left blank, 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 continuously (loop body, then increment step value, 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 results:
a 的值: 10 a 的值: 11 a 的值: 12 a 的值: 13 a 的值: 14 a 的值: 15 a 的值: 16 a 的值: 17 a 的值: 18 a 的值: 19other extensions