RustArena

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

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

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

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.

Previous: while loops Next: break and continue