B. fn factorial(n: u32) -> u32 { while n > 0 { n * factorial(n - 1) } }
C. fn factorial(n: u32) -> u32 { if n == 0 { 1 } else { n * factorial(n - 1) } }
D. fn factorial(n: u32) -> u32 { return n + factorial(n - 1); }
Solution
Step 1: Check base case and recursive call
fn factorial(n: u32) -> u32 { if n == 0 { 1 } else { n * factorial(n - 1) } } correctly uses if n == 0 { 1 } as base case and recursive multiplication.
Step 2: Identify syntax errors in other options
fn factorial(n: u32) -> u32 { while n > 0 { n * factorial(n - 1) } } uses while loop incorrectly, C loops infinitely, D uses addition instead of multiplication.
Final Answer:
fn factorial(n: u32) -> u32 { if n == 0 { 1 } else { n * factorial(n - 1) } } -> Option C
Quick Check:
Correct base case and recursive call = fn factorial(n: u32) -> u32 { if n == 0 { 1 } else { n * factorial(n - 1) } } [OK]
Hint: Look for base case with if and recursive call with smaller input [OK]
Common Mistakes:
Using loops instead of recursion
Missing base case
Wrong operation in recursive call
3. What is the output of this Rust code?
fn sum(n: u32) -> u32 {
if n == 0 {
0
} else {
n + sum(n - 1)
}
}
fn main() {
println!("{}", sum(3));
}
The function lacks a base case like if n == 0 { 1 } to stop recursion.
Step 2: Understand recursion consequences
Without base case, recursion never stops, causing stack overflow error.
Final Answer:
Missing base case to stop recursion -> Option A
Quick Check:
Base case missing = Missing base case to stop recursion [OK]
Hint: Always include base case to stop recursion [OK]
Common Mistakes:
Assuming recursion stops automatically
Ignoring base case importance
Confusing return types
5. You want to write a recursive function in Rust to find the nth Fibonacci number. Which of the following correctly shows the base case and recursive case?
hard
A. if n == 0 { 0 } else if n == 1 { 1 } else { fib(n - 1) + fib(n - 2) }
B. if n == 1 { 0 } else if n == 2 { 1 } else { fib(n - 1) * fib(n - 2) }
C. if n == 0 { 1 } else { fib(n - 1) + fib(n - 2) }
D. if n == 0 { 0 } else { fib(n - 1) - fib(n - 2) }
Solution
Step 1: Identify correct base cases for Fibonacci
Fibonacci sequence starts with fib(0) = 0 and fib(1) = 1, so base cases must reflect that.
Step 2: Check recursive case correctness
Recursive case sums previous two Fibonacci numbers: fib(n-1) + fib(n-2).
Final Answer:
if n == 0 { 0 } else if n == 1 { 1 } else { fib(n - 1) + fib(n - 2) } -> Option A
Quick Check:
Correct base and recursive case for Fibonacci = if n == 0 { 0 } else if n == 1 { 1 } else { fib(n - 1) + fib(n - 2) } [OK]
Hint: Fibonacci base cases: 0 and 1; recursive case sums previous two [OK]
Common Mistakes:
Wrong base case values
Using multiplication or subtraction instead of addition
Missing one base case
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.