Step 5 of 7
for loops and ranges
To repeat something a known number of times, or once for each value in a sequence, use for. The simplest sequence is a range of numbers:
fn main() {
for round in 1..4 {
println!("round {round}");
}
let mut total = 0;
for n in 1..=100 {
total += n;
}
println!("sum of 1 to 100 = {total}");
}
round 1
round 2
round 3
sum of 1 to 100 = 5050
for round in 1..4runs the body once for each value in the range, withroundset to that value. The loop variable is a fresh variable each time, and it only exists inside the loop.a..bis a half-open range: fromaup to but not includingb. So0..nruns exactlyntimes, with the values 0 to n - 1.a..=bis an inclusive range: it includesb.- If you don't need the value, call it
_:for _ in 0..3 { println!("hip hip hooray"); }.
Backwards, and in steps
fn main() {
for i in (1..=3).rev() {
print!("{i} ");
}
println!("liftoff");
for even in (0..=10).step_by(2) {
print!("{even} ");
}
println!();
}
3 2 1 liftoff
0 2 4 6 8 10
.rev()runs a range backwards. The parentheses around the range are needed:1..=3.rev()would try to call.rev()on the number3..step_by(2)takes every second value.println!()with nothing inside just ends the line.
Why for is usually the best choice
You could count with while:
let mut i = 0;
while i < 5 {
println!("{i}");
i += 1;
}
But for i in 0..5 can't forget the i += 1, can't get stuck, and shows the whole range at a glance. In Rust, for is the everyday loop; while and loop are for when you don't know in advance how many iterations you need. Later you'll use for with lists and text too: it works with anything that produces a sequence of values (an iterator).
Common mistakes
- Off-by-one with
..:for i in 1..10stops at 9. Use1..=10to include 10. - Counting down with a "backwards" range:
for i in 5..1runs zero times. To count 5, 4, 3, 2, 1, write(1..=5).rev(). - Changing the loop variable to skip ahead: the next value comes from the range anyway (and the loop variable is immutable). Use
.step_by()orcontinue(next step).
Your task
Print the 7 times table, from 7 x 1 = 7 to 7 x 10 = 70, one line each, using a for loop with a single println! inside.
Challenge 2
Print the even numbers from 20 down to 0 on one line (separated by spaces), then Go! on the next line:
20 18 16 14 12 10 8 6 4 2 0
Go!
Use one for loop over a range with .rev() and .step_by(2).
Challenge 3
Write fn sum_of_multiples(limit: u32) -> u32 that adds up every number below limit that is a multiple of 3 or of 5. For example, below 10 these are 3, 5, 6 and 9, which sum to 23. Use a for loop.