Challenge - 5 Problems
Loop Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ Predict Output
intermediate2:00remaining
Output of nested loops with break
What is the output of this Rust code snippet?
Rust
fn main() {
let mut count = 0;
for i in 1..=3 {
for j in 1..=3 {
if i * j > 4 {
break;
}
count += 1;
}
}
println!("{}", count);
}Attempts:
2 left
๐ก Hint
Count how many times the inner loop runs before break triggers.
โ Incorrect
The inner loop breaks when i*j > 4. Counting iterations: i=1 (j=1,2,3) all <=4, count=3; i=2 (j=1,2) 2*3=6>4 break at j=3, count=5; i=3 (j=1) 3*2=6>4 break at j=2, count=6 total.
โ Predict Output
intermediate2:00remaining
Loop with continue and variable update
What will be printed by this Rust program?
Rust
fn main() {
let mut sum = 0;
for x in 1..=5 {
if x % 2 == 0 {
continue;
}
sum += x;
}
println!("{}", sum);
}Attempts:
2 left
๐ก Hint
Sum only odd numbers from 1 to 5.
โ Incorrect
The loop skips even numbers (2,4). Sum is 1 + 3 + 5 = 9.
๐ง Debug
advanced2:00remaining
Identify the error in this loop
What error will this Rust code produce when compiled?
Rust
fn main() {
let mut i = 0;
loop {
if i == 5 {
break;
}
i += 1;
}
println!("{}", i);
}Attempts:
2 left
๐ก Hint
Check if all statements end properly.
โ Incorrect
The original code was missing a semicolon after 'i += 1'. Adding the semicolon fixes the syntax error, so the code compiles and prints 5.
โ Predict Output
advanced2:00remaining
Loop with labeled break
What will this Rust program print?
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
The labeled break exits both loops when i+j == 4.
โ Incorrect
The labeled break exits the outer loop when i+j == 4. For i=1: j=1 (2!=4) count=1; j=2 (3!=4) count=2; j=3 (4==4) break 'outer (no increment). No further iterations. Total count=2.
โ Predict Output
expert2:00remaining
Complex loop with multiple control flow statements
What is the final value of `result` after running this Rust code?
Rust
fn main() {
let mut result = 0;
let mut i = 0;
while i < 5 {
i += 1;
if i == 3 {
continue;
}
if i == 4 {
break;
}
result += i;
}
println!("{}", result);
}Attempts:
2 left
๐ก Hint
Trace each iteration and note when continue and break happen.
โ Incorrect
i=1 result=1; i=2 result=3; i=3 continue (skip adding); i=4 break loop; final result=3.