Looping with for
for i in 0..10 — a concise range loop, with break and continue.
Looping with for
The while pattern we just learned — counting from zero to a limit — is so common that AHA! Lang provides a more concise form: for with a number range.
Basic Form
for i in 0..5 {
print(i);
}Output:
0
1
2
3
4Structure:
for <variable> in <start>..<end> {
...code to repeat...
}- The variable (e.g.
i) automatically holds the current round's value. - The range
0..5means: start from 0, up to but not including 5 (5 is not included). This is called an exclusive end. - No need to declare or increment a counter manually — the compiler handles it all.
How Many Times Does the Loop Run?
for i in 0..3 { print(i); } // 0, 1, 2 → 3 times
for i in 1..4 { print(i); } // 1, 2, 3 → 3 times
for i in 0..1 { print(i); } // 0 → 1 time
for i in 0..0 { print(i); } // (nothing) → 0 timesThe formula: the range a..b runs b - a rounds.
Summing with for
Remember the 1..100 exercise with while? The for version is much shorter:
let total = 0;
for i in 1..101 {
total = total + i;
}
print(total); // 5050break and continue in for
Same as while:
// break: stop early
let total = 0;
for i in 0..100 {
if i == 5 {
break;
}
total = total + i;
}
print(total); // 0 + 1 + 2 + 3 + 4 = 10// continue: skip one round
let jumlah_ganjil = 0;
for i in 0..10 {
if i % 2 == 0 {
continue;
}
jumlah_ganjil = jumlah_ganjil + i;
}
print(jumlah_ganjil); // 1 + 3 + 5 + 7 + 9 = 25Using the Loop Variable
The range variable can be used in any calculation:
// multiplication table of 7
for i 1..11 {
print(7 * i);
}
// 7, 14, 21, ..., 70while or for?
| Situation | Choose |
|---|---|
| You know exactly how many rounds (number range) | for |
| The loop depends on a changing condition | while |
| You want to step through elements in increments (2, 4, 6, ...) | while with a manual counter |
Both have break/continue, so you can start with whichever feels most natural.
Exercises
- Print all even numbers from 0 to 20 using
forandi % 2. - Compute the product
1 * 2 * 3 * ... * 10(factorial of 10) — start fromhasil = 1. - Print the squares from 1 to 10 (
i * i). - Combine
forandif: count how many numbers from 1 to 50 are divisible by 5.
On to Functions