0
0
Rustprogramming~20 mins

While loop in Rust - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
๐ŸŽ–๏ธ
Rust While Loop Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ“ Predict Output
intermediate
2:00remaining
Output of a simple while loop
What is the output of this Rust program?
Rust
fn main() {
    let mut count = 0;
    while count < 3 {
        println!("{}", count);
        count += 1;
    }
}
A0\n1\n2
B1\n2\n3
C0\n1\n2\n3
D1\n2
Attempts:
2 left
๐Ÿ’ก Hint
Remember the loop runs while count is less than 3, starting from 0.
โ“ Predict Output
intermediate
2:00remaining
While loop with break condition
What will this Rust program print?
Rust
fn main() {
    let mut n = 5;
    while n > 0 {
        if n == 3 {
            break;
        }
        println!("{}", n);
        n -= 1;
    }
}
A5\n4\n3
B4\n3\n2\n1
C5\n4
D5\n4\n2\n1
Attempts:
2 left
๐Ÿ’ก Hint
The loop stops when n equals 3 before printing it.
๐Ÿ”ง Debug
advanced
2:00remaining
Identify the error in this while loop
What error will this Rust code produce when compiled?
Rust
fn main() {
    let mut i = 0;
    while i < 5 {
        println!("{}", i);
        i = i + 1;
    }
}
ARuntimeError: infinite loop
BSyntaxError: expected `;` after expression
CTypeError: mismatched types
DNo error, prints 0 to 4
Attempts:
2 left
๐Ÿ’ก Hint
Check the line endings inside the loop.
โ“ Predict Output
advanced
2:00remaining
While loop with nested if and continue
What is the output of this Rust program?
Rust
fn main() {
    let mut x = 0;
    while x < 5 {
        x += 1;
        if x % 2 == 0 {
            continue;
        }
        println!("{}", x);
    }
}
A0\n1\n3\n5
B2\n4
C1\n2\n3\n4\n5
D1\n3\n5
Attempts:
2 left
๐Ÿ’ก Hint
The continue skips printing even numbers.
๐Ÿง  Conceptual
expert
3:00remaining
While loop behavior with mutable references
Consider this Rust code snippet. What will be the value of `counter` after the loop finishes?
Rust
fn main() {
    let mut counter = 0;
    let mut reference = &mut counter;
    while *reference < 4 {
        *reference += 1;
    }
    println!("{}", counter);
}
A4
B0
C5
DCompilation error due to mutable borrow
Attempts:
2 left
๐Ÿ’ก Hint
The mutable reference changes the original variable inside the loop.