Looping with For
In the last chapter, you learned how to repeat code with while loops. Now let's learn about for loops — a cleaner way to loop when you know exactly how many times you want to repeat something!
Counting with Ranges
A range tells Rust to count from one number to another. Here's how to print the numbers 0 through 4:
The 0..5 part is called a range. It starts at 0 and goes up to (but not including) 5. So you get: 0, 1, 2, 3, 4.
Notice how much simpler this is compared to a while loop — no mut variable, no manual counting!
Inclusive Ranges
What if you want to include the last number? Use ..= instead of ..:
This prints 1, 2, 3, 4, 5 — the = sign means "include the end number too!"
| Range | Numbers you get |
|---|---|
0..5 | 0, 1, 2, 3, 4 |
1..=5 | 1, 2, 3, 4, 5 |
1..4 | 1, 2, 3 |
1..=4 | 1, 2, 3, 4 |
Skipping Numbers with step_by
Want to count by twos? Or threes? Use .step_by():
This prints 0, 2, 4, 6, 8. Notice the parentheses around the range — they're needed when you call .step_by() on a range.
Looping Over Characters
You can loop through the letters in a string using .chars():
This prints each character on its own line: h, e, l, l, o.
Looping Over a Vector
A vector is like a list of items. You can loop through it with .iter():
Using the Loop Variable
The loop variable (like i or ch) changes each time through the loop. You can use it for all kinds of things:
Summary
| Concept | What it does |
|---|---|
for i in 0..5 | Loop with i = 0, 1, 2, 3, 4 |
for i in 1..=5 | Loop with i = 1, 2, 3, 4, 5 |
(0..10).step_by(2) | Loop with i = 0, 2, 4, 6, 8 |
"text".chars() | Loop through each character |
vec.iter() | Loop through each item in a vector |
Now let's practice using for loops!