Definition
A for loop is a control structure used in programming to repeat a block of code a specific number of times. It typically consists of three parts:
- Initialization: Sets a starting value.
- Condition: The loop continues as long as this is true.
- Update: Changes the loop variable after each iteration.
The general syntax in many languages (like C, Java, or Python) is:
- C/Java:
- Python:
- Initialization: $i = 1$
- Condition: $i \leq 5$
- Update: $i$ increases by $1$ each time The loop prints $1, 2, 3, 4, 5$.
- A for loop repeats code a set number of times, controlled by a loop variable.
- The three main parts are initialization, condition, and update.
- Syntax varies by language, but the logic is the same: start, continue while true, update.
```
for (initialization; condition; update) {
// code block
}
`
for variable in range(start, stop, step):
code block
`
Worked Example
Example: Print the numbers from 1 to 5.
C/Java-style
`c`
for (int i = 1; i <= 5; i++) {
printf("%dn", i);
}
Python-style
`python``
for i in range(1, 6):
print(i)
Explanation: