0
0
Rustprogramming~20 mins

Loop construct 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 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);
}
A6
B9
C5
D4
Attempts:
2 left
๐Ÿ’ก Hint
Remember that break with label exits the outer loop immediately.
๐Ÿง  Conceptual
intermediate
1:30remaining
Understanding loop labels in Rust
Which statement best describes the purpose of loop labels in Rust?
AThey automatically count the number of iterations.
BThey are used to name variables inside loops.
CThey define the type of loop (for, while, or loop).
DThey allow breaking or continuing an outer loop from inside an inner loop.
Attempts:
2 left
๐Ÿ’ก Hint
Think about how to control nested loops.
โ“ Predict Output
advanced
2: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);
}
A7
B9
C10
D15
Attempts:
2 left
๐Ÿ’ก Hint
Remember that continue skips the rest of the loop body for that iteration.
๐Ÿ”ง Debug
advanced
1: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;
    }
}
ASyntaxError: missing semicolon after i = i + 1
BRuntimeError: infinite loop
CTypeError: cannot add integer to mutable variable
DNo error, prints numbers 0 to 4
Attempts:
2 left
๐Ÿ’ก Hint
Check punctuation carefully in Rust statements.
๐Ÿš€ Application
expert
3: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?
A
let mut sum = 0;
for n in 1..=10 {
    if n % 2 == 0 { continue; }
    sum += n;
}
println!("{}", sum);
B
let mut sum = 0;
let mut n = 1;
loop {
    if n &gt; 10 { break; }
    if n % 2 != 0 { n += 1; continue; }
    sum += n;
    n += 1;
}
println!("{}", sum);
C
let mut sum = 0;
let mut n = 1;
while n &lt;= 10 {
    if n % 2 == 0 { sum += n; }
    n += 1;
}
println!("{}", sum);
D
let mut sum = 0;
let mut n = 1;
loop {
    if n &gt; 10 { break; }
    if n % 2 == 0 { sum += n; }
    n += 1;
}
println!("{}", sum);
Attempts:
2 left
๐Ÿ’ก Hint
Use continue to skip odd numbers inside the loop.