For Loop: Over a range
● Beginner3 min
Loop over a range of numbers: .. leaves the end out, ..= puts it in.
fn main() {
for i in 0..3 {
print(i)
}
for i in 1..=3 {
print(i)
}
}The program ran and printed:
kavach run range.kav
012123
0..3 is 0, 1, 2. 1..=3 is 1, 2, 3. Ranges that leave the end out join without overlap: 0..n then n..m never counts n twice.
One past the end
A list's last index is len() - 1, so a loop to ..=items.len() reads one item too many and panics on its last turn. The compiler warns before it runs:
fn main() {
const items = ["tea", "milk"]
for i in 0..=items.len() {
print(items[i])
}
}The compiler warned, then the program ran:
kavach run one-past.kav
warning: `i` reaches `items.len()`, one past the last index of `items`, so `items[i]` panics on the last turn: write `..` instead of `..=`, or loop over `items` itself (spec 4.4)teamilkpanic: index 2 is out of range: the list has 2 items
Write 0..items.len(), or better, for item in items, which can't go past the end. A loop that changes the list, or reads it at another index, gets no warning.
What Kavach does for you
Ranges say which end they mean
0..10stops before 10;0..=10includes it. Non - 1orn + 1to get wrong.