Syntax
The for loop repeats a block of code a specific number of times. It has three parts: initializer, condition, and increment.
for (initializer; condition; increment) {
// code to repeat
}
Example
void main() {
// Count 1 to 5
for (int i = 1; i <= 5; i++) {
print('Count: $i');
}
// Sum of 1 to 100
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum += i;
}
print('Sum 1–100: $sum'); // 5050
// Loop backwards
for (int i = 5; i >= 1; i--) {
print('Countdown: $i');
}
}
Output (partial):Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Sum 1–100: 5050
Countdown: 5 ... 1
For-In Loop
Iterate over every element in a collection without a counter:
List<String> fruits = ['apple', 'banana', 'cherry'];
for (String fruit in fruits) {
print(fruit);
}
// apple banana cherry
forEach()
Collections also have a forEach() method that accepts a function:
fruits.forEach((fruit) => print(fruit.toUpperCase()));
// APPLE BANANA CHERRY
💪 Exercise
- Print the multiplication table for 7 (7×1 to 7×10).
- Print all even numbers between 1 and 20.
- Calculate the factorial of 10 using a for loop.
🧠 Quiz
1. What are the three parts of a for loop?
- A) start, stop, step ✅ (initializer, condition, increment)
- B) init, body, end
- C) begin, check, next
- D) value, range, step
2. Which loop is best for iterating over a List?
- A) while
- B) do-while
- C) for-in ✅
- D) repeat
Summary
The for loop repeats a block a set number of times with an initializer, condition, and increment. Use for-in to iterate over collections. Use forEach() for functional-style iteration with a callback.