Lesson 3
Conditions and loops
if as an expression, the three ways to repeat, ranges, loop labels, break with a value, and continue.
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.
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.
Objective
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.
Implement
Replace `todo!` with a `while n != 1` loop and an `if`/`else` for even/odd.
Function 01
Count the Collatz steps
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")
}Check
Run the visible cases and use the diagnostic to correct the code.
Visible tests
Modify the code before running the tests.
Help
View progressive hints or compare with the solution.
/// Counts the steps the Collatz sequence takes to reach 1 from `start`.
#[must_use]
pub fn collatz_steps(start: u64) -> u32 {
let mut n = start;
let mut steps = 0;
while n != 1 {
if n % 2 == 0 {
n /= 2;
} else {
n = 3 * n + 1;
}
steps += 1;
}
steps
}
// Playground entry point for this example.
fn main() {
println!("{}", collatz_steps(6));
}Summary
ifis an expression: it produces a value, and its two branches must have the same type.looprepeats until an explicitbreak;whilechecks its condition before each turn;forwalks a range or iterator.- Ranges
../..=exclude or include the end; a label ('outer) identifies which loop should break when several are nested. break 'labelexits the outer loop directly, with no extra flags.continuejumps to the next turn without running the rest of the body.break valueends aloopand that value becomes the result of the loop.