For Loop
When you know the exact number of times you need to loop through a block of code, use a for
loop instead of a while
loop.
Syntax
for (expression 1; expression 2; expression 3) { } |
- Expression 1 is executed once before the code block starts.
- Expression 2 sets the condition for running the code block.
- Expression 3 is executed after each iteration of the code block.
The following example will print the numbers 0 through 4:
Example
int i;
for (i = 0; i < 5; i++) { printf(“%d\n”, i); } |
Example explained
- Expression 1 initializes a variable before the loop begins (int i = 0).
- Expression 2 sets the condition for the loop to continue (i must be less than 5). If the condition is true, the loop will repeat; if false, the loop will terminate.
- Expression 3 increments the value (i++) after each iteration of the code block.