Challenge - 5 Problems
Loop Labels Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ Predict Output
intermediate2:00remaining
Output of nested loops with labels
What is the output of this Rust code using loop labels?
Rust
fn main() {
let mut count = 0;
'outer: loop {
println!("Outer loop start");
'inner: loop {
count += 1;
if count == 2 {
break 'outer;
}
break 'inner;
}
println!("Outer loop end");
}
println!("Count: {}", count);
}Attempts:
2 left
๐ก Hint
Look at where the break statements with labels exit the loops.
โ Incorrect
The outer loop runs twice. First: prints 'Outer loop start', inner increments count to 1 and breaks 'inner', prints 'Outer loop end'. Second: prints 'Outer loop start', inner increments to 2 and breaks 'outer' without printing 'Outer loop end'. Then prints 'Count: 2'.
โ Predict Output
intermediate2:00remaining
Value of variable after labeled loops
What is the value of variable `i` after running this Rust code?
Rust
fn main() {
let mut i = 0;
'counting_up: loop {
i += 1;
'counting_down: loop {
i -= 1;
break 'counting_up;
}
}
println!("i = {}", i);
}Attempts:
2 left
๐ก Hint
Check which loop the break statement exits and when increments/decrements happen.
โ Incorrect
The outer loop increments i to 1, then the inner loop decrements i to 0 and breaks the outer loop. Final value i = 0.
๐ง Debug
advanced2:00remaining
Identify the error with loop labels
What error does this Rust code produce?
Rust
fn main() {
let mut x = 0;
'outer: loop {
'inner: loop {
if x > 5 {
break 'outer;
}
x += 1;
break 'inner;
}
break 'inner;
}
println!("x = {}", x);
}Attempts:
2 left
๐ก Hint
Check where the break statements with labels are used relative to their loops.
โ Incorrect
The break 'inner outside the inner loop causes a compile error because it tries to break to a label not in scope at that point.
๐ Syntax
advanced2:00remaining
Which option correctly uses loop labels to break outer loop?
Which code snippet correctly breaks the outer loop from inside the inner loop using labels?
Attempts:
2 left
๐ก Hint
Remember the syntax for labeling loops and breaking to labels.
โ Incorrect
Option A uses correct syntax: 'outer: before outer loop and break 'outer; inside inner loop. A breaks to undefined 'inner, B has invalid label position after loop, C misses ' in break outer.
๐ Application
expert2:00remaining
How many times does the inner loop run?
Consider this Rust code. How many times does the inner loop execute before the program ends?
Rust
fn main() {
let mut count = 0;
'outer: loop {
'inner: loop {
count += 1;
if count == 3 {
break 'outer;
}
break 'inner;
}
}
println!("Count: {}", count);
}Attempts:
2 left
๐ก Hint
Count how many times the inner loop increments before breaking the outer loop.
โ Incorrect
The inner loop runs once per outer loop iteration. It increments count and breaks inner loop unless count == 3, then breaks outer loop. So inner loop runs 3 times total.