0
0
Rustprogramming~20 mins

Loop with break in Rust - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
๐ŸŽ–๏ธ
Rust Loop Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ“ Predict Output
intermediate
2: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);
}
A0
B5
C10
DCompilation error
Attempts:
2 left
๐Ÿ’ก Hint
The loop breaks when count reaches 5 and returns count * 2.
โ“ Predict Output
intermediate
2: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);
}
ACompilation error
Bi = 3, j = 3
Ci = 1, j = 1
Di = 1, j = 3
Attempts:
2 left
๐Ÿ’ก Hint
The break with label exits the outer loop when j reaches 3.
๐Ÿ”ง Debug
advanced
2: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);
}
ASyntaxError: missing semicolon after x += 1
BTypeError: cannot break with a value
CNo error, prints 4
DRuntimeError: infinite loop
Attempts:
2 left
๐Ÿ’ก Hint
Check punctuation carefully inside the loop.
โ“ Predict Output
advanced
2: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);
}
A(3, 7)
B(4, 9)
C(4, 5)
DCompilation error
Attempts:
2 left
๐Ÿ’ก Hint
The loop breaks when a becomes greater than 3, returning (a, b).
๐Ÿง  Conceptual
expert
2: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?
A10, because the loop breaks exactly when n reaches 10
B9, because the break happens before incrementing n to 10
CCompilation error due to missing break value
DInfinite loop, because break has no value
Attempts:
2 left
๐Ÿ’ก Hint
The break without a value just exits the loop; n increments before the check.