Module 03 Exercises — Control Flow & Functions
How to use this page
Attempt every exercise in a real Cargo project before opening a solution — a solution you have not fought for teaches almost nothing. Tick the boxes as you go; progress is saved in this browser.
Before you start, make sure you can explain:
- why a block ending in
5and one ending in5;are different; - when you would choose
loopoverwhile; - what
()means when it turns up in an error message.
The drills below deliberately provoke the semicolon error. Getting it three or four times here is how it stops costing you time forever.
Part A — Warm-Up Drills
Short reps on the mechanics. Do them until the syntax stops costing you any thought.
🟢 Exercise 3.1 — FizzBuzz
Print 1..=100, replacing multiples of 3 with Fizz, of 5 with Buzz, of both with
FizzBuzz. Write it twice: once with if/else if, once with a match on
(n % 3, n % 5).
Solution
fn main() {
for n in 1..=100 {
match (n % 3, n % 5) {
(0, 0) => println!("FizzBuzz"),
(0, _) => println!("Fizz"),
(_, 0) => println!("Buzz"),
_ => println!("{n}"),
}
}
}The match version is exhaustive by construction — you can't forget a case.
🟢 Exercise 3.2 — Predict the output
fn main() {
let x = {
let a = 2;
a + 3;
};
println!("{x:?}");
}Answer
Prints (). The trailing semicolon discards a + 3, so the block evaluates to unit.
(Note {x:?} is needed because () has no Display impl.)
Part B — Core Exercises
The real practice. Attempt each one fully — compiler errors included — before opening a solution.
🟡 Exercise 3.3 — Collatz
Write fn collatz_steps(mut n: u64) -> u32 returning how many steps it takes to reach 1
(even → n/2, odd → 3n+1). Then find the starting value under 1000 with the most steps.
Solution
fn collatz_steps(mut n: u64) -> u32 {
let mut steps = 0;
while n != 1 {
n = if n % 2 == 0 { n / 2 } else { 3 * n + 1 };
steps += 1;
}
steps
}
fn main() {
let mut best = (1u64, 0u32);
for start in 1..1000 {
let s = collatz_steps(start);
if s > best.1 { best = (start, s); }
}
println!("{} takes {} steps", best.0, best.1); // 871 takes 178 steps
}🟡 Exercise 3.4 — Prime sieve with labels
Print all primes below 50 using a nested loop and a labelled continue — no Vec, no
helper function.
Solution
fn main() {
'candidate: for n in 2..50u32 {
let mut d = 2;
while d * d <= n {
if n % d == 0 { continue 'candidate; }
d += 1;
}
print!("{n} ");
}
println!();
}🟡 Exercise 3.5 — Guessing game
Using rand and std::io, write the classic guessing game: pick a secret 1..=100, read
lines from stdin, respond "too small" / "too big" / "you win", loop until correct, and
ignore non-numeric input instead of crashing.
Solution
use rand::Rng;
use std::io::{self, Write};
fn main() {
let secret = rand::thread_rng().gen_range(1..=100);
loop {
print!("Guess: ");
io::stdout().flush().unwrap();
let mut line = String::new();
if io::stdin().read_line(&mut line).is_err() { continue; }
let guess: u32 = match line.trim().parse() {
Ok(n) => n,
Err(_) => { println!("Please type a number."); continue; }
};
if guess < secret { println!("Too small!"); }
else if guess > secret { println!("Too big!"); }
else { println!("You win!"); break; }
}
}The match on parse() is your first real taste of Result handling — module 08.
Part C — Challenges
Longer builds. Expect to fight the borrow checker here; that fight is the lesson.
🔴 Exercise 3.6 — Loop as an expression
Write a function fn find_root(target: f64) -> f64 that computes a square root using
Newton's method, using loop { ... break value } to return as soon as the guess is within
1e-10. Do not use while, and do not use f64::sqrt.
Solution
fn find_root(target: f64) -> f64 {
let mut guess = target / 2.0;
loop {
let next = (guess + target / guess) / 2.0;
if (next - guess).abs() < 1e-10 {
break next;
}
guess = next;
}
}
fn main() {
println!("{:.10}", find_root(2.0)); // 1.4142135624
assert!((find_root(144.0) - 12.0).abs() < 1e-9);
}Self-check
- Why does adding a semicolon to the last line of a function often cause an E0308?
- Which loop can return a value via
break? - What is the type of
if x > 0 { 1 }when there is noelse? - Why must function parameters be type-annotated?
- What does the
!return type mean?
Answers
- The semicolon turns the expression into a statement, so the block evaluates to
()instead of the declared return type. loop(and any labelled loop viabreak 'label value).()— which is why it can't be assigned to a numeric binding.- So type checking and error messages stay local to one function and signatures act as compiler-verified documentation.
- The function never returns (it loops forever, panics, or exits);
!coerces to any type.
Next: Module 04 — Ownership
