Rullst AcademyRullst Academy/Lesson
Rust: from idea to program · Lesson 04 / 08

Repeat with a beginning and an end

The robot collects one, two and three parts at three stations. Instead of copying statements, we will traverse a sequence with for.

Learning paths9 min

Let's discover together

  1. 1

    for value in 1..4 visits 1, 2 and 3. The start is included; the end after .. is excluded. Each iteration runs the block once.

  2. 2

    An accumulator starts with a value and is updated each iteration: let mut total = 0; and, inside the block, total += value;.

  3. 3

    Trace the states: start at 0, add 1 to get 1; add 2 to get 3; add 3 to finish at 6. Writing these states helps explain the loop.

  4. 4

    1..=4 includes 4 and makes four iterations. But 0..0 contains no values and makes zero iterations. A for loop ends when its sequence ends.

✦
YOUR MISSION

Predict how many iterations a loop makes, the total and what changes with an inclusive range.

Now it's your turn

Discovery workshop

Trace the parts collection

Code under investigation: total starts at 0; for each value in 1..4, we do total += value.
Build your answers and check when you are ready.
A moment to understand

Which range includes the number 4?

I need a hint

The = sign includes the endpoint.

Loading your journey…

Take it with you

Make a table for 2..5: current value and total after adding. Then predict 0..0 without executing it.

Show me the Rust behind it

This part is optional. You don't need to memorize the code to continue.

fn main() {
    let mut total = 0;
    for value in 1..4 {
        total += value;
    }
    println!("{total}");
}
At your own pace

My files and GitHub

Every lesson can become your own record: code, notes or a practice plan. Saving a file to GitHub is optional and does not change your XP.

Student guide

The editor and downloads open when this lesson is available to your account. Check access below or return to the track map.

Checking your access to this lesson…

Rullstpetbot

AI can make mistakes. Check the lesson material.