Challenge - 5 Problems
Rust Loop Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ Predict Output
intermediate2:00remaining
Output of a nested loop with break
What is the output of this Rust code snippet?
Rust
fn main() {
let mut count = 0;
'outer: for i in 1..=3 {
for j in 1..=3 {
if i * j > 4 {
break 'outer;
}
count += 1;
}
}
println!("{}", count);
}Attempts:
2 left
๐ก Hint
Remember that break with label exits the outer loop immediately.
โ Incorrect
The inner loop increments count while i*j <= 4. When i=2 and j=3, i*j=6 > 4, so break 'outer stops all loops. The count increments 5 times before breaking.
๐ง Conceptual
intermediate1:30remaining
Understanding loop labels in Rust
Which statement best describes the purpose of loop labels in Rust?
Attempts:
2 left
๐ก Hint
Think about how to control nested loops.
โ Incorrect
Loop labels let you specify which loop to break or continue when loops are nested, avoiding ambiguity.
โ Predict Output
advanced2:00remaining
Output of a loop with match and continue
What is the output of this Rust program?
Rust
fn main() {
let mut x = 0;
let mut result = 0;
loop {
x += 1;
match x {
3 => continue,
5 => break,
_ => result += x,
}
}
println!("{}", result);
}Attempts:
2 left
๐ก Hint
Remember that continue skips the rest of the loop body for that iteration.
โ Incorrect
The loop adds x to result except when x is 3 (skips adding) and stops when x is 5. So result = 1+2+4 = 7 + 5 skipped + break at 5.
๐ง Debug
advanced1:30remaining
Identify the error in this loop code
What error will this Rust code produce when compiled?
Rust
fn main() {
let mut i = 0;
while i < 5 {
println!("{}", i);
i = i + 1;
}
}Attempts:
2 left
๐ก Hint
Check punctuation carefully in Rust statements.
โ Incorrect
Rust requires semicolons at the end of statements. Missing semicolon after i = i + 1 causes a syntax error.
๐ Application
expert3:00remaining
Calculate sum of even numbers using loop and continue
Which Rust code correctly calculates the sum of even numbers from 1 to 10 using a loop and continue?
Attempts:
2 left
๐ก Hint
Use continue to skip odd numbers inside the loop.
โ Incorrect
Option B uses loop and continue correctly to skip odd numbers and sum even numbers. Option B incorrectly continues on even numbers. Option B uses while but no continue. Option B sums even numbers but does not use continue.