Challenge - 5 Problems
Rust Nested Conditions Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ Predict Output
intermediate2:00remaining
Output of nested if-else blocks
What is the output of this Rust code snippet?
Rust
fn main() {
let x = 7;
if x > 5 {
if x < 10 {
println!("A");
} else {
println!("B");
}
} else {
println!("C");
}
}Attempts:
2 left
๐ก Hint
Check the conditions step by step: is x greater than 5? Is it less than 10?
โ Incorrect
The variable x is 7, which is greater than 5 and less than 10, so the inner if prints "A".
โ Predict Output
intermediate2:00remaining
Nested match with conditions output
What will this Rust program print?
Rust
fn main() {
let num = 3;
match num {
1..=5 => {
if num % 2 == 0 {
println!("Even");
} else {
println!("Odd");
}
}
_ => println!("Out of range"),
}
}Attempts:
2 left
๐ก Hint
Check if 3 is between 1 and 5, then check if it is even or odd.
โ Incorrect
3 is between 1 and 5, and 3 % 2 is 1 (odd), so it prints "Odd".
๐ง Debug
advanced2:00remaining
Identify the error in nested if conditions
This Rust code does not compile. What is the error?
Rust
fn main() {
let x = 10;
if x > 5 {
if x < 15 {
println!("Inside");
}
} else {
println!("Outside");
}
}Attempts:
2 left
๐ก Hint
Look at how Rust matches else with the nearest if.
โ Incorrect
The else is matched with the inner if, but the outer if lacks braces, causing a syntax error.
โ Predict Output
advanced2:00remaining
Output of nested if with else if
What does this Rust program print?
Rust
fn main() {
let score = 85;
if score >= 90 {
println!("A");
} else if score >= 80 {
if score >= 85 {
println!("B+");
} else {
println!("B");
}
} else {
println!("C");
}
}Attempts:
2 left
๐ก Hint
Check the score against each condition carefully.
โ Incorrect
Score 85 is not >= 90, but >= 80 and also >= 85, so it prints "B+".
๐ง Conceptual
expert2:00remaining
How many times is the inner block executed?
Consider this Rust code snippet. How many times will the inner println! be executed?
Rust
fn main() {
for i in 1..=5 {
if i % 2 == 0 {
if i > 2 {
println!("{}", i);
}
}
}
}Attempts:
2 left
๐ก Hint
Check which numbers from 1 to 5 are even and greater than 2.
โ Incorrect
Only 4 and 2 are even, but 2 is not greater than 2, so only 4 is printed. Also 4 is the only number printed, so 1 time.