0
0
Rustprogramming~20 mins

If–else expression in Rust - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
If–else Expression Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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);
}
Asmall
BCompilation error
C10
Dbig
Attempts:
2 left
💡 Hint
Check the condition x > 5 and what the if–else expression returns.
Predict Output
intermediate
2: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);
}
A4
B3
C6
DCompilation error
Attempts:
2 left
💡 Hint
Check if a is even or odd and what the if–else expression returns.
Predict Output
advanced
2: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);
}
Alarge
Bsmall
Cmedium
DCompilation error
Attempts:
2 left
💡 Hint
Check the conditions in order and see which branch matches n = 7.
Predict Output
advanced
2: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);
}
ARuntime panic
BType mismatch error
CCompilation succeeds and prints 10
DCompilation succeeds and prints "ten"
Attempts:
2 left
💡 Hint
Check the types returned by the if and else branches.
🧠 Conceptual
expert
2: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?
ABecause Rust uses static typing and the expression must have a single, known type at compile time.
BBecause Rust allows dynamic typing only inside if–else expressions.
CBecause the else branch is optional and can be omitted.
DBecause Rust automatically converts all types to strings in if–else expressions.
Attempts:
2 left
💡 Hint
Think about how Rust checks types before running the program.