Exerpad
🔥1
10 XP
Lv.1 Beginner
Log In

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:

rust
fn main() {
for i in 0..5 {
println!("{}", i);
}
}

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 ..:

rust
fn main() {
for i in 1..=5 {
println!("{}", i);
}
}

This prints 1, 2, 3, 4, 5 — the = sign means "include the end number too!"

RangeNumbers you get
0..50, 1, 2, 3, 4
1..=51, 2, 3, 4, 5
1..41, 2, 3
1..=41, 2, 3, 4

Skipping Numbers with step_by

Want to count by twos? Or threes? Use .step_by():

rust
fn main() {
for i in (0..10).step_by(2) {
println!("{}", i);
}
}

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():

rust
fn main() {
for ch in "hello".chars() {
println!("{}", ch);
}
}

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():

rust
fn main() {
let colors = vec!["red", "green", "blue"];
for color in colors.iter() {
println!("I like {}!", color);
}
}

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:

rust
fn main() {
for i in 1..=3 {
println!("{} times 2 is {}", i, i * 2);
}
}

Summary

ConceptWhat it does
for i in 0..5Loop with i = 0, 1, 2, 3, 4
for i in 1..=5Loop 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!