Skip to content
Theory · Conditions and Loops · lesson 3 of 6

loop and while

In the previous lesson the program chose a road at a fork. Now let's teach it to repeat the same steps.

Picture a runner at a stadium. They run lap after lap on the same track until the coach says "enough". A program often needs to repeat things too: count laps, go through numbers, search for the right value. For this there is the loop, a block of code that runs again and again. We'll call one run of this block a pass.

Rust has three loops: loop, while and for. Let's start with loop: it repeats its block with no condition at all, until break stops it.

Rust
fn main() {
    let mut lap = 0;
    loop {
        lap += 1;
        if lap == 3 {
            break;
        }
    }
    println!("laps: {lap}"); // laps: 3
}

Let's go through the program step by step:

  1. let mut lap = 0; sets up a lap counter. It is mutable, because the loop will change it.
  2. loop { starts the loop: everything up to the matching } repeats.
  3. lap += 1; adds one to lap, the same as lap = lap + 1;.
  4. On the third pass the condition lap == 3 is true, and break ends the loop.
  5. The program continues after the loop and prints laps: 3.

Without break this loop would never end. It is called an infinite loop, and that is how you write, for example, a server that keeps waiting for new requests.

break and continue

Two instructions inside the block change the usual course of the passes. Both usually sit inside an if.

break

break ends the whole loop at once. The rest of the block and all later passes are skipped, and the program continues from the line after the loop. The runner leaves the track.

continue

continue skips only the rest of the current pass and starts the next one right away. The loop does not end: the runner cuts the rest of the lap short and runs a new one.

People often mix them up, and the difference is big: break ends the whole loop, continue only the current pass.

A value from loop

A loop often searches for something, and what it finds has to be saved in a variable. In Rust, loop, like if, is an expression. You can write a value after break: break leaves the loop, and this value becomes the value of the whole loop. This program searches for the first number whose square is greater than 50:

Rust
let mut n = 1;
let found = loop {
    if n * n > 50 {
        break n;
    }
    n += 1;
};
println!("{found}"); // 8

Let's go through it step by step:

  1. The loop checks the numbers in turn: 1, 2, 3 and so on.
  2. While n * n is not greater than 50, n += 1 moves on to the next number. The square of 7 is 49, and the loop goes on.
  3. The square of 8 is 64, and break n leaves the loop with the value 8.
  4. let found = puts the value of the whole loop into found, and the program prints 8.

break takes the whole expression after it: break n * 2 would give 16, not 8. The loop ends right at break, so the line n += 1 no longer runs on the last pass. The semicolon after } ends the let instruction, as in the line with if.

Here is the same rule on a running track: the runner runs 400-meter laps until reaching 1000 meters, and the loop gives back the number of laps. Press "Next step" and watch when the variable laps appears in the main frame.

LiveA value from loopstep 1 of 13 · frames: 1

The runner is at the start: meters is 0, and there is no laps variable yet.

Watch when laps appears in the main frame

Interviewers like to ask this: "How do you return a value from a loop?" The answer: with loop and break with a value, let x = loop { … break value; };.

The while loop

while repeats its block as long as the condition is true. The condition is checked before every pass and, as in if, must have type bool. This program counts how many times 100 has to be divided by 2 with integer division until 1 is left:

Rust
let mut n = 100;
let mut steps = 0;
while n > 1 {
    n = n / 2;
    steps += 1;
}
println!("{steps} steps, n = {n}"); // 6 steps, n = 1

The values of n go like this: 100, 50, 25, 12, 6, 3, 1. After the sixth division the condition n > 1 becomes false, and the loop ends without any break.

You use while when the number of passes is not known in advance and depends on what happens inside the loop. Here the runner picture is inaccurate: a runner runs at least one lap, while while checks the condition before the very first pass. If the condition is false right away, the block does not run even once.

Common mistake

The search from the found example is rewritten with while, and the break with a value is kept:

Rust
fn main() {
    let mut n = 1;
    let found = while n < 100 {
        if n * n > 50 {
            break n; // ✗
        }
        n += 1;
    };
}
TEXT
error[E0571]: `break` with value from a `while` loop

The program does not compile. A while loop can also end without break, when its condition becomes false, and then there would be nothing to give back. That is why only loop gives a value through break, and a search with a value is written with loop, as in the example above.

Key points

  • loop repeats its block until break stops it; continue skips the rest of a pass.
  • loop is an expression: break value leaves the loop and makes value the value of the whole loop.
  • while checks a bool condition before every pass and may run zero times.
  • break with a value is allowed only in loop: in while it is error E0571.