Challenge - 5 Problems
Rust For Loop Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ Predict Output
intermediate2:00remaining
What is the output of this Rust for loop?
Consider the following Rust code. What will it print?
Rust
fn main() {
let mut sum = 0;
for i in 1..5 {
sum += i;
}
println!("{}", sum);
}Attempts:
2 left
๐ก Hint
Remember that 1..5 in Rust means 1 up to but not including 5.
โ Incorrect
The loop runs for i = 1, 2, 3, 4. Their sum is 1+2+3+4 = 10.
๐ง Conceptual
intermediate1:30remaining
How many times does this Rust for loop run?
How many iterations will this loop execute?
for x in (0..10).step_by(3) {
println!("{}", x);
}
Attempts:
2 left
๐ก Hint
Count numbers from 0 to 9 stepping by 3.
โ Incorrect
The loop runs for x = 0, 3, 6, 9, so 4 times.
โ Predict Output
advanced2:30remaining
What is the output of this nested for loop?
Analyze the output of this Rust code snippet:
Rust
fn main() {
for i in 1..3 {
for j in 1..=i {
print!("{}{} ", i, j);
}
}
}Attempts:
2 left
๐ก Hint
Remember that 1..3 means 1 and 2, and 1..=i includes i.
โ Incorrect
Outer loop i=1: inner j=1 prints '11 '. Outer loop i=2: inner j=1,2 prints '21 22 '.
๐ง Debug
advanced2:00remaining
What error does this Rust for loop code produce?
Identify the error when running this code:
Rust
fn main() {
let mut numbers = vec![1, 2, 3];
for num in numbers.iter() {
numbers.push(*num + 1);
}
}Attempts:
2 left
๐ก Hint
Think about modifying a vector while looping over it.
โ Incorrect
You cannot mutate a vector by pushing to it while iterating over it, causing a compile error.
๐ Application
expert3:00remaining
What is the final value of `result` after this loop?
Given this Rust code, what is the value of `result` after the loop finishes?
Rust
fn main() {
let mut result = 1;
for i in (1..=4).rev() {
if i % 2 == 0 {
result *= i;
}
}
println!("{}", result);
}Attempts:
2 left
๐ก Hint
Multiply only even numbers from 4 down to 1.
โ Incorrect
Even numbers in 4..=1 reversed are 4 and 2. Multiplying 1*4*2 = 8.