RustArena

Step 4 of 6

Looping over an array

Arrays shine when you combine them with loops: one piece of code that handles every element, however many there are. There are two ways to loop.

Loop over the elements

fn main() {
    let temps = [18, 21, 19, 25, 23];
    let mut sum = 0;
    for t in temps {
        sum += t;
    }
    println!("sum: {sum}");
    println!("average: {:.1}", sum as f64 / temps.len() as f64);
}
sum: 106
average: 21.2

for t in temps runs the body once per element, in order, with t set to each one. No index, so no way to go out of bounds. This is the pattern for totals, counts and searches. Note the average: both numbers are converted to f64 with as so the division keeps its fraction.

Loop over the indexes

When you need the position as well as the value, loop over the range 0..temps.len(), which is exactly the valid indexes (0, 1, 2, 3, 4):

fn main() {
    let temps = [18, 21, 19, 25, 23];
    let mut hottest = 0; // index of the hottest day so far
    for i in 0..temps.len() {
        if temps[i] > temps[hottest] {
            hottest = i;
        }
    }
    println!("hottest: day {} with {} degrees", hottest + 1, temps[hottest]);
}
hottest: day 4 with 25 degrees

Changing every element

In for t in temps, t is a copy of each element: changing t doesn't touch the array. To change the elements, use the index:

fn main() {
    let mut prices = [120, 75, 300];
    for i in 0..prices.len() {
        prices[i] = prices[i] * 110 / 100; // +10%, in whole cents
    }
    println!("{:?}", prices);
}
[132, 82, 330]

At work: Rust programmers write for x in array whenever they don't need the index. Clippy's needless_range_loop lint points out index loops that could be simpler, and suggests iterator methods (.iter(), .iter_mut(), .enumerate()) that you'll learn in modules 16 and 27. Until then, index loops are the right tool when you need the position or want to change elements.

Common mistakes

Your task

Write count_above(temps, limit), which returns how many of the seven days were strictly warmer than limit. For example, with temperatures [18, 25, 30, 22, 31, 19, 26] and limit 25, three days (30, 31 and 26) count.

Challenge 2

Write max_value(values), which returns the largest of six numbers. Careful: the numbers can all be negative.

Challenge 3

A sale takes 20% off every price. Prices are whole cents, so compute the new price with integer math: price * 80 / 100. Change the array itself with an index loop, then print the array and the new total:

[96, 60, 240, 36]
total: 432

Previous: Arrays: a fixed row of values Next: Grids: arrays of arrays