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 loop with break returning a value
What is the output of this Rust program?
Rust
fn main() {
let mut count = 0;
let result = loop {
count += 1;
if count == 5 {
break count * 2;
}
};
println!("{}", result);
}Attempts:
2 left
๐ก Hint
The loop breaks when count reaches 5 and returns count * 2.
โ Incorrect
The loop increments count from 0 to 5. When count is 5, it breaks and returns 5 * 2 = 10. This value is stored in result and printed.
โ Predict Output
intermediate2:00remaining
Loop with break inside nested loops
What will be printed by this Rust code?
Rust
fn main() {
let mut i = 0;
let mut j = 0;
'outer: loop {
i += 1;
loop {
j += 1;
if j == 3 {
break 'outer;
}
}
}
println!("i = {}, j = {}", i, j);
}Attempts:
2 left
๐ก Hint
The break with label exits the outer loop when j reaches 3.
โ Incorrect
The inner loop increments j until it reaches 3, then breaks the outer loop. i was incremented once before entering inner loop, so i=1 and j=3.
๐ง Debug
advanced2:00remaining
Identify the error in loop with break
What error does this Rust code produce?
Rust
fn main() {
let mut x = 0;
let y = loop {
x += 1;
if x > 3 {
break x;
}
};
println!("{}", y);
}Attempts:
2 left
๐ก Hint
Check punctuation carefully inside the loop.
โ Incorrect
The line 'x += 1' is missing a semicolon, causing a syntax error.
โ Predict Output
advanced2:00remaining
Loop with break returning a tuple
What is the output of this Rust program?
Rust
fn main() {
let mut a = 0;
let mut b = 1;
let result = loop {
if a > 3 {
break (a, b);
}
a += 1;
b += 2;
};
println!("{:?}", result);
}Attempts:
2 left
๐ก Hint
The loop breaks when a becomes greater than 3, returning (a, b).
โ Incorrect
a increments from 0 to 4, b increments by 2 each time from 1 to 9. When a is 4 (>3), loop breaks returning (4,9).
๐ง Conceptual
expert2:00remaining
Behavior of break in infinite loop with condition
Consider this Rust code snippet:
fn main() {
let mut n = 0;
loop {
n += 1;
if n == 10 {
break;
}
}
println!("{}", n);
}
What is the value printed and why?
Attempts:
2 left
๐ก Hint
The break without a value just exits the loop; n increments before the check.
โ Incorrect
n starts at 0, increments to 10, then break exits the loop. The printed value is 10.