C For Loop
For Loop
a for loop is a control structure used to repeat a block of code a specific number of times. It's a versatile tool for iterating through data structures like arrays or lists, and for performing repetitive tasks. Here's a breakdown of its components:
Syntax
for (expression 1; expression 2; expression 3) {
// code block to be executed
}
Steps 1 Initialization: int i = 1; declares an integer variable i and initializes it to 1. This is the starting value for the loop.
Steps 2 Condition: i <= 5;
checks if the value of i is less than or equal to 5. This is the condition that determines how long the loop will run.
Steps 3 Body: The code inside the curly braces {} is the body of the loop. In this case, printf("%d ", i);
prints the value of i followed by a space.
Steps 4 Increment: ++i;
increases the value of i by 1 after each iteration of the loop.
Steps 5 Iteration: Steps 2-4 are repeated as long as the condition remains true. In this case, the loop will run 5 times because i starts at 1 and is incremented to 2, 3, 4, and 5, each time satisfying the condition i <= 5
.
Steps 4 Termination: Once the condition i <= 5
becomes false (when i reaches 6), the loop terminates.
The example below will print the numbers 0 to 4:
Syntax
#include <stdio.h>
int main() {
int i;
for (i = 0; i < 5; i++) {
printf("%d\n", i);
}
return 0;
}
Output
0
1
2
3
4
Example explained
Expression 1 sets a variable before the loop starts (int i = 0).
Expression 2 defines the condition for the loop to run (i must be less than 5). If the condition is true, the loop will start over again, if it is false, the loop will end.
Expression 3 increases a value (i++) each time the code block in the loop has been executed.