Small Programs · 11 min · free lesson

Loops

Choose the loop form that states why repetition ends.

Core idea

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

Coming from C? From for(;;) to Ranges covers this side by side.

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.

Read the code

let mut count = 0;
let answer = loop {
    count += 1;
    if count == 3 { break count; }
};
println!("{answer}");

break returns count as the value of the loop expression.

Practice starter

let value = loop {
    break 7;
};

Practise this code in Playground ↗

Three flows compare for, while, and loop, with break leaving an unconditional loop.
Use a for loop for iteration, a while loop for a condition, and loop when an explicit break decides when to stop.

Work through it

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. while repeats while its boolean condition remains true; it is useful when the condition itself is the central idea. An unconditional loop makes sense when the body must inspect data before deciding to stop, but every path through it should have a comprehensible exit plan. continue jumps to the next pass without running the remainder of the current body.

Trace count on paper for each iteration and mark exactly where the break happens. Then rewrite a three-pass task with for index in 0..3 and compare the two versions. If you remove the break from the original loop, ask whether the program can ever finish. The most readable loop is the one whose termination rule a reader can see immediately.

When choosing a loop form, ask whether the collection owns the elements after iteration. Iterating over &items borrows; iterating over items can move its elements. Try both and inspect whether the original collection is still available after the loop.

Choose a loop based on what controls repetition. A for loop is natural when you already have a range or collection to traverse. A while loop repeats while a condition stays true. A plain loop continues until a break or other exit. Whichever form you choose, identify the state that changes and the condition that eventually stops the work. An accidental infinite loop is usually a missing state update or a boundary that can never be reached.

Trace the example for all three iterations in a table: count before, condition, body effect, count after. Then run your for rewrite over an empty range and a one-item range and count the passes. If you need both position and value, enumerate() often reads better than manual indexing. A break can also return a value from loop; a continue skips to the next iteration. Use each only when it makes the exit path easier to see.

Try it

Sum all integers from 1 through n, inclusive, using a loop. Inputs are in 0..=100. In the Crabrix app, open the compiler lab and complete the supplied function in solution.rs. The reading question is a separate exercise.

What success looks like: The local compiler accepts the changed solution and the separate verification harness finishes all normal and boundary cases. Printing a success message alone does not complete this lab.

Check your understanding

What is stored in value?

Reveal the answer
  1. ()
  2. 7
  3. true

A value after break becomes the value produced by the loop expression.

One more experiment

Change count == 3 to count == 5 and predict the output. Then replace break count; with a bare break; and write the diagnostic you expect from the println! line.

Learn this lesson with AI

Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.

I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools.
Lesson: Loops (courseId "basics", lessonId "loops")
Link: https://crabrix.com/learn/basics/loops/
Goal: Prefer for for iteration; use loop when break defines the exit.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=basics/loops) and I will write the code there.
Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.

In Claude Code, Codex or Cursor, paste it into a chat with Crabrix Academy connected. On a phone, the Claude and ChatGPT apps open the same links.