Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to make the function call itself recursively.
DSA Rust
fn factorial(n: u32) -> u32 {
if n == 0 {
1
} else {
n * factorial([1])
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using n + 1 causes infinite recursion.
Using 0 or 1 directly in the recursive call breaks the logic.
✗ Incorrect
The function calls itself with n - 1 to reduce the problem size until it reaches 0.
2fill in blank
mediumComplete the code to correctly calculate the nth Fibonacci number recursively.
DSA Rust
fn fibonacci(n: u32) -> u32 {
if n == 0 || n == 1 {
n
} else {
fibonacci([1]) + fibonacci(n - 2)
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using n - 2 for both calls.
Using n + 1 causes infinite recursion.
✗ Incorrect
The Fibonacci number is the sum of the two previous numbers: fibonacci(n-1) + fibonacci(n-2).
3fill in blank
hardFix the error in the recursive function to avoid infinite recursion.
DSA Rust
fn countdown(n: i32) {
if n == 0 {
println!("Blast off!");
} else {
println!("{}", n);
countdown([1]);
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using n + 1 causes infinite recursion.
Calling with n does not change the state.
✗ Incorrect
The function must call countdown with n - 1 to move towards the base case and stop recursion.
4fill in blank
hardFill both blanks to create a recursive function that sums numbers from 1 to n.
DSA Rust
fn sum_to_n(n: u32) -> u32 {
if n == 0 {
0
} else {
n + sum_to_n([1])
}
}
fn main() {
let result = sum_to_n([2]);
println!("Sum is {}", result);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using n + 1 in recursion causes infinite loop.
Calling sum_to_n with 0 in main returns 0 immediately.
✗ Incorrect
The recursive call reduces n by 1 each time, and the main function calls sum_to_n with 5 to sum 1 through 5.
5fill in blank
hardFill all three blanks to create a recursive function that reverses a string.
DSA Rust
fn reverse_string(s: &str) -> String {
if s.is_empty() {
String::new()
} else {
let first_char = s.chars().next().unwrap();
let rest = &s[[1]..];
format!("{}{}", reverse_string(rest), [2])
}
}
fn main() {
let word = "hello";
let reversed = reverse_string([3]);
println!("Reversed: {}", reversed);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using 0 in slice causes infinite recursion.
Appending the whole string instead of first_char breaks reversal.
✗ Incorrect
The function slices the string from index 1 to end, recursively reverses it, then appends the first character. The main function passes the original word.
