Challenge - 5 Problems
If–else Expression Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of a simple if–else expression
What is the output of this Rust code snippet?
Rust
fn main() {
let x = 10;
let y = if x > 5 { "big" } else { "small" };
println!("{}", y);
}Attempts:
2 left
💡 Hint
Check the condition x > 5 and what the if–else expression returns.
✗ Incorrect
The variable y is assigned the string "big" because x is 10, which is greater than 5.
❓ Predict Output
intermediate2:00remaining
If–else expression with numeric result
What value does variable result hold after running this code?
Rust
fn main() {
let a = 3;
let result = if a % 2 == 0 { a * 2 } else { a + 1 };
println!("{}", result);
}Attempts:
2 left
💡 Hint
Check if a is even or odd and what the if–else expression returns.
✗ Incorrect
Since 3 is odd, the else branch runs, so result is 3 + 1 = 4.
❓ Predict Output
advanced2:00remaining
Nested if–else expression output
What is printed by this Rust program?
Rust
fn main() {
let n = 7;
let description = if n < 5 {
"small"
} else if n < 10 {
"medium"
} else {
"large"
};
println!("{}", description);
}Attempts:
2 left
💡 Hint
Check the conditions in order and see which branch matches n = 7.
✗ Incorrect
7 is not less than 5, but it is less than 10, so the second branch runs.
❓ Predict Output
advanced2:00remaining
If–else expression with mismatched types
What error does this Rust code produce?
Rust
fn main() {
let flag = true;
let value = if flag { 10 } else { "ten" };
println!("{:?}", value);
}Attempts:
2 left
💡 Hint
Check the types returned by the if and else branches.
✗ Incorrect
The if branch returns an integer, the else branch returns a string slice, causing a type mismatch error.
🧠 Conceptual
expert2:00remaining
Why must if–else expressions have matching types?
In Rust, why must the if and else branches of an if–else expression return the same type?
Attempts:
2 left
💡 Hint
Think about how Rust checks types before running the program.
✗ Incorrect
Rust is statically typed, so every expression must have a single, known type at compile time. If branches return different types, the compiler cannot determine the expression's type.