Challenge - 5 Problems
Rust While Loop Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ Predict Output
intermediate2: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;
}
}Attempts:
2 left
๐ก Hint
Remember the loop runs while count is less than 3, starting from 0.
โ Incorrect
The loop starts with count = 0 and prints it. It increments count by 1 each time. It stops before count reaches 3, so it prints 0, 1, and 2.
โ Predict Output
intermediate2: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;
}
}Attempts:
2 left
๐ก Hint
The loop stops when n equals 3 before printing it.
โ Incorrect
The loop prints n while n is greater than 0. When n reaches 3, the break stops the loop before printing 3. So it prints 5 and 4 only.
๐ง Debug
advanced2: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;
}
}Attempts:
2 left
๐ก Hint
Check the line endings inside the loop.
โ Incorrect
Rust requires semicolons at the end of statements. The line `i = i + 1` is missing a semicolon, causing a syntax error.
โ Predict Output
advanced2: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);
}
}Attempts:
2 left
๐ก Hint
The continue skips printing even numbers.
โ Incorrect
The loop increments x first. If x is even, it skips printing. So only odd numbers 1, 3, and 5 are printed.
๐ง Conceptual
expert3: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);
}Attempts:
2 left
๐ก Hint
The mutable reference changes the original variable inside the loop.
โ Incorrect
The mutable reference `reference` points to `counter`. The loop increments the value through the reference until it reaches 4. So `counter` becomes 4.