Rust Fundamentals · 15 XP Pro

while loops

while checks a condition before every round and stops as soon as it is false. If the condition is false the first time, the body never runs at all.

let mut countdown = 3;
while countdown > 0 {
    println!("{countdown}");
    countdown -= 1;
}

while is a good fit when the loop is driven by a changing value rather than by a fixed number of rounds. Something inside the body must move the value toward making the condition false, otherwise you have written an infinite loop.

A classic trick: n / 10 drops the last decimal digit of an integer, and n % 10 reads it.

let mut n = 472;
while n > 0 {
    let digit = n % 10; // 2, then 7, then 4
    n /= 10;
}

Your task

  1. Write count_digits(n: u64) -> u32 that returns how many decimal digits n has. Treat 0 as having one digit.
  2. Write collatz_steps(n: u64) -> u32. Starting from n (at least 1), repeat: if the number is even, halve it; if odd, replace it with 3 * n + 1. Return how many steps it takes to reach 1. For example 6 -> 3 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1 is 8 steps.

Next lesson →

Sign in to run your code. It's free.