Find the error in this nested condition Rust code:
fn main() {
let x = 3;
if x > 0
if x < 5 {
println!("x is between 1 and 4");
}
}
medium
A. The println! macro is used wrongly.
B. Incorrect comparison operators used.
C. Variable x is not declared.
D. Missing braces for the outer if block.
Solution
Step 1: Check syntax of outer if
The outer if lacks braces, so the inner if is not properly nested.
Step 2: Understand Rust's block requirements
Rust requires braces to group nested blocks clearly; missing braces cause syntax errors.
Final Answer:
Missing braces for the outer if block. -> Option D
Quick Check:
Braces needed for nested if blocks [OK]
Hint: Always use braces {} for nested if blocks [OK]
Common Mistakes:
Skipping braces for nested if
Misreading comparison operators
Assuming println! usage is wrong
5.
Write a nested condition in Rust that prints:
"Small and even" if a number is less than 10 and even,
"Small and odd" if less than 10 and odd,
"Large number" if 10 or more.
Which code snippet correctly implements this?
fn main() {
let n = 8;
// Choose the correct nested condition
}
hard
A. if n < 10 {
if n % 2 == 0 {
println!("Small and even");
} else {
println!("Small and odd");
}
} else {
println!("Large number");
}
B. if n % 2 == 0 {
if n < 10 {
println!("Small and even");
} else {
println!("Large number");
}
} else {
println!("Small and odd");
}
C. if n < 10 && n % 2 == 0 {
println!("Small and even");
} else if n < 10 {
println!("Small and odd");
} else {
println!("Large number");
}
D. if n < 10 {
println!("Small and even");
} else if n % 2 == 0 {
println!("Large number");
} else {
println!("Small and odd");
}
Solution
Step 1: Check outer condition for number size
if n < 10 {
if n % 2 == 0 {
println!("Small and even");
} else {
println!("Small and odd");
}
} else {
println!("Large number");
} first checks if n < 10, then inside checks even or odd.
Step 2: Verify inner conditions and outputs
If even, prints "Small and even"; else prints "Small and odd". If not less than 10, prints "Large number".
Final Answer:
Option A correctly implements the nested conditions as described. -> Option A
Quick Check:
Outer size check, inner even/odd check = if n < 10 {
if n % 2 == 0 {
println!("Small and even");
} else {
println!("Small and odd");
}
} else {
println!("Large number");
} [OK]
Hint: Check outer condition first, then inner even/odd [OK]
Common Mistakes:
Checking even before size
Mixing up print messages
Using flat conditions instead of nested
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.