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..4yields 0, 1, 2, 3 (the end is excluded)0..=4yields 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)jumpsnat 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
sum_to(n: u32) -> u32: the sum of every whole number from1toninclusive (0whennis0).sum_every(step: usize, limit: u32) -> u32: the sum of0, step, 2*step, ...for every value up to and includinglimit. Usestep_by.stepis at least 1.countdown(n: u32) -> String: the numbers fromndown to1, separated by single spaces, with no trailing space.countdown(3)is"3 2 1"andcountdown(0)is"". Hint:i.to_string()turns a number into aString, andformat!("{out} {i}")builds a new one.