Complete the code to make the function call itself recursively.
func factorial(n int) int {
if n == 0 {
return 1
}
return n * factorial([1])
}The recursive call must reduce the problem size by 1 each time, so we use n-1.
Complete the code to correctly calculate the sum of numbers from 1 to n using recursion.
func sumToN(n int) int {
if n == 0 {
return 0
}
return n + sumToN([1])
}The function calls itself with n-1 to add all numbers down to 0.
Fix the error in the recursive Fibonacci function to avoid infinite recursion.
func fibonacci(n int) int {
if n == 0 {
return 0
} else if n == 1 {
return 1
}
return fibonacci([1]) + fibonacci(n-2)
}The function must call fibonacci with n-1 and n-2 to correctly compute Fibonacci numbers.
Fill both blanks to create a recursive function that counts down from n to 1.
func countdown(n int) {
if n == 0 {
return
}
fmt.Println(n)
countdown([1])
fmt.Println([2])
}The function calls itself with n-1 to count down, and prints n after the recursive call to show the call stack unwinding.
Fill all three blanks to create a recursive function that reverses a string.
func reverse(s string) string {
if len(s) == 0 {
return ""
}
return reverse(s[1]) + string(s[2])
}The function calls itself with the substring from index 1 onward (s[1:]), then adds the first character (s[0]) at the end.
