Learn/Rust/5. Loops
Lesson 5 of 15
Sign in

Rust, lesson 5

Loops

Rust has three loops: for to walk over a sequence, while to repeat while a condition holds, and loop to repeat until you explicitly stop.

for over a range

for walks over anything that can be iterated. The most common thing to iterate is a range:

a..b includes a but stops before b. a..=b includes b. To count down, reverse the range: for n in (1..=3).rev(). To step by more than one: for n in (0..10).step_by(2).

2 exercises to try what you just read.

Exercise 1

Times table

Press Ctrl Enter or Check to test your code.

Exercise 2

Savings goal

Press Ctrl Enter or Check to test your code.

If you do not need the loop variable, name it _: for _ in 0..3 { ... }.

while

while repeats as long as its condition is true:

A close cousin is while let, which keeps looping as long as a value matches a pattern. It is perfect for draining a stack: pop() gives Some(item) until the vector is empty, then None, which ends the loop.

loop

loop repeats forever until a break. It suits "keep going until something happens". A special feature: break can carry a value out, making the whole loop an expression.

break and continue

break leaves the loop. continue skips the rest of this pass and starts the next:

In nested loops, both act on the innermost loop. To target an outer loop, give it a label, which starts with an apostrophe:

Looping over input

Reading numbers until the input runs out is a natural for loop over split_whitespace():

To work line by line, use input.lines(), or iterate std::io::stdin().lines(), which yields each line as a Result<String>.

Accumulators

Many loops build up a result: a sum starts at 0, a product at 1, a maximum at the first value. Declare the accumulator with let mut before the loop so it survives between passes.

Further reading

  • The Rust Book: Repetition with loops
  • Rust by Example: for and range
  • Rust by Example: Nesting and labels

Read a whole number n and print its times table from 1 to 10, one line each, as n x i = result.

Sample input:

Sample output (first and last lines):

Read weekly deposits (whole numbers separated by whitespace) until the input runs out, adding them up. As soon as the running total reaches 100 or more, print goal reached in week N (week 1 is the first number) and stop. If the input ends first, print total so far: T.

Sample input:

Sample output:

for lap in 1..4 {
    println!("lap {lap}"); // 1, 2, 3
}
for n in 1..=3 {
    println!("{n}");       // 1, 2, 3
}
let mut balance = 100;
while balance > 0 {
    balance -= 30;
}
println!("{balance}"); // -20
let mut stack = vec![1, 2, 3];
while let Some(top) = stack.pop() {
    println!("{top}"); // 3, 2, 1
}
let mut n = 1;
let first_big_square = loop {
    if n * n > 50 {
        break n * n;
    }
    n += 1;
};
println!("{first_big_square}"); // 64
for i in 0..10 {
    if i % 2 == 0 {
        continue;
    }
    if i > 7 {
        break;
    }
    print!("{i} ");
}
// 1 3 5 7
'outer: for r in 0..3 {
    for c in 0..3 {
        if r * c == 2 {
            break 'outer;
        }
    }
}
let input = std::io::read_to_string(std::io::stdin()).unwrap();
let mut total = 0;
for word in input.split_whitespace() {
    let n: i32 = word.parse().unwrap();
    total += n;
}
7
7 x 1 = 7
7 x 2 = 14
...
7 x 10 = 70
30 25 40 10 50
goal reached in week 4