Rust Fundamentals · 15 XP Pro

for loops and ranges

for walks through a sequence of values, giving you each one in turn. The most common sequence is a range:

  • 0..4 yields 0, 1, 2, 3 (the end is excluded)
  • 0..=4 yields 0, 1, 2, 3, 4 (the end is included)
for i in 1..=3 {
    println!("round {i}");
}

Two adapters change how a range is walked:

  • .rev() runs it backwards: (1..=3).rev() gives 3, 2, 1
  • .step_by(n) jumps n at a time: (0..10).step_by(3) gives 0, 3, 6, 9

Wrap the range in parentheses before calling a method on it. There is no counter to get wrong and no way to run off the end, which is why for is preferred over while whenever you know what you are looping over.

Your task

  1. sum_to(n: u32) -> u32: the sum of every whole number from 1 to n inclusive (0 when n is 0).
  2. sum_every(step: usize, limit: u32) -> u32: the sum of 0, step, 2*step, ... for every value up to and including limit. Use step_by. step is at least 1.
  3. countdown(n: u32) -> String: the numbers from n down to 1, separated by single spaces, with no trailing space. countdown(3) is "3 2 1" and countdown(0) is "". Hint: i.to_string() turns a number into a String, and format!("{out} {i}") builds a new one.

Next lesson →

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