Small Programs · 11 min · free with an account

Loops

Lesson preview · about 30%

Choose the loop form that states why repetition ends.

Core idea

Prefer for for iteration; use loop when break defines the exit.

Start with the idea

for consumes an iterator, while repeats while a condition remains true, and loop has no condition at all. A loop expression can return a value with break value. continue skips directly to the next iteration. Selecting the narrowest form makes termination easier to see and accidental infinite work harder to write.

The example chooses loop because the end condition is written inside the body. count starts at zero, increases once per pass, and when it reaches three, break count exits with the value 3. That value becomes answer. A bare break would yield (), so the type of answer depends on what every possible exit produces. This is a loop expression, not just a repeated statement.

For a known sequence, for usually says more with less code: it asks an iterator for the next item and stops when there are none.

Keep learning, for free

The rest of this lesson is waiting for you.

Create a free account to read the complete explanation, see the infographic, explore the code, and try the exercises. All 742 lessons and algorithm steps are included.

No payment details. Your account opens the complete Academy.

← All lessons in Rust Basics