Lesson 3

Conditions and loops

if as an expression, the three ways to repeat, ranges, loop labels, break with a value, and continue.

Level
Beginner
Duration
22 min
Updated

Three ways to repeat, and a name for each loop

In “Variables, functions and control flow” you already used if and for informally, without naming why if produces a value or that two other ways to repeat exist. Here we complete the vocabulary: loop, while, and for cover different cases, and ranges, labels, and break/continue give you fine control over when to stop.

This vocabulary reappears through the rest of the course: iterators, match, and later the ? operator all build on the same expression and control-flow ideas you see here.

You will go through four stations: if as an expression, the three ways to repeat, ranges and labels, and the two ways to exit a loop.

Flow state

  • CONDITION · n < 0Boolean result
  • PATH · both branches: i32same type in both branches
  • RESULT · clamp_lowclamp_low(-5), clamp_low(5)
01 / 04IF · ELSE · SAME TYPE

Exercise 01 · Collatz conjecture

Count how many steps a Collatz sequence takes to reach 1.

The starter already declares the signature. Complete the body with a `while` loop that applies the even/odd rule each turn until it reaches 1.

0/1correct

Complete collatz_steps so it counts the steps: if n is even, divide by 2; if odd, compute 3 * n + 1. Repeat until n equals 1 and return the number of steps taken.

01

Implement

Replace `todo!` with a `while n != 1` loop and an `if`/`else` for even/odd.

Function 01

Count the Collatz steps

Unchanged

Repeat the even/odd rule until reaching 1, counting one turn for each step applied.

/// Counts the steps the Collatz sequence takes to reach 1 from `start`.
pub fn collatz_steps(start: u64) -> u32 {
    todo!("loop while n != 1: even -> n / 2, odd -> 3 * n + 1, count each step")
}
02

Check

Run the visible cases and use the diagnostic to correct the code.

counts the correct steps for several known sequences
Compiler

Modify the code before running the tests.

03

Help

View progressive hints or compare with the solution.

Run an attempt to unlock the solution.

Summary

  • if is an expression: it produces a value, and its two branches must have the same type.
  • loop repeats until an explicit break; while checks its condition before each turn; for walks a range or iterator.
  • Ranges ../..= exclude or include the end; a label ('outer) identifies which loop should break when several are nested.
  • break 'label exits the outer loop directly, with no extra flags.
  • continue jumps to the next turn without running the rest of the body.
  • break value ends a loop and that value becomes the result of the loop.

Sources