RustArena

Step 3 of 7

loop and break

Programs often repeat work. The simplest way is loop, which repeats its block forever, until you stop it with break:

fn main() {
    let mut countdown = 3;
    loop {
        println!("{countdown}");
        countdown -= 1;
        if countdown == 0 {
            break;
        }
    }
    println!("Go!");
}
3
2
1
Go!

Each run through the block is an iteration. break exits the loop immediately, and the program continues after the loop's closing brace.

Getting a value out of a loop

loop is an expression too: break value ends the loop and makes value the result of the whole loop. That's perfect for "keep trying until something happens, then tell me the answer":

fn main() {
    let mut n = 1;
    let first_big_square = loop {
        if n * n > 500 {
            break n * n;
        }
        n += 1;
    };
    println!("first square above 500: {first_big_square} ({n} x {n})");
}
first square above 500: 529 (23 x 23)

When a loop is the final expression of a function, break value gives the function its return value. Inside a function, return also leaves a loop (and the whole function) immediately.

Infinite loops

If no break is ever reached, the loop runs forever and the program hangs. On this site, a run is stopped after 2 seconds ("time limit exceeded"); on your computer, press Ctrl+C. Some programs loop forever on purpose: a game's main loop or a server waiting for requests runs until it's told to quit.

Common mistakes

Your task

Write fn smallest_power_of_two(n: u32) -> u32 that returns the smallest power of two (1, 2, 4, 8, 16, ...) that is greater than or equal to n. Start at 1 and keep doubling inside a loop; break with the answer.

Challenge 2

Fill in the blanks so the countdown loops until it reaches zero and then stops. It should print 3, 2, 1 and liftoff on separate lines.

Challenge 3

Write fn years_to_double(start: u32, rate_percent: u32) -> u32. A savings balance begins at start, and each year it grows by balance * rate_percent / 100 (integer division). Return how many years it takes until the balance is at least twice start. Use loop and break with the number of years. (You can assume start is at least 100 and the rate at least 1.)

Previous: if is an expression Next: while loops