C Language | Flow Control | for Statement
The for statement places loop initialization, a condition, and an update expression in one construct.
Counter-Controlled Loops
The syntax is:
for (initialization; condition; update) statement
It corresponds to:
initialization;
while (condition) {
statement;
update;
}
All three expressions may be omitted. With no condition, the loop is infinite: for (;;) { ... }.
#include <stdio.h>
int main(void) {
int iMax, iCount;
printf("Enter the number of repetitions. >");
for (scanf("%d", &iMax), iCount = 0; iCount < iMax; iCount++)
printf("iteration %d\n", iCount);
return 0;
}
The comma between arguments in scanf() is a separator. The comma between scanf(...) and iCount = 0 is the comma operator, which evaluates expressions from left to right. It can be useful in a for expression, but excessive use reduces readability.
Loops can be nested.
for (iOp1 = 1; iOp1 < 10; iOp1++) {
for (iOp2 = 1; iOp2 < 10; iOp2++)
printf("%2d ", iOp1 * iOp2);
printf("\n");
}
This prints a multiplication table.