Write a recursive function
Write a recursive function
A recursive function calls itself to solve a smaller instance of a problem. It needs a base case that returns without another recursive call and a step that moves toward that base case. Each call has its own parameter values.
package main
import "fmt"
func sumTo(n int) int { if n <= 0 { return 0 } return n + sumTo(n-1)}func main() { fmt.Println(sumTo(4))}The calls expand to 4 + 3 + 2 + 1 + 0. The base case returns 0, then the pending additions complete as calls return. This example defines nonpositive inputs to return zero and is intended for small inputs.
Use a loop for simple accumulation
package main
import "fmt"
func sumTo(n int) int { total := 0 for i := 1; i <= n; i++ { total += i } return total}func main() { fmt.Println(sumTo(4)) fmt.Println(sumTo(0))}The loop computes the same result for small inputs without recursive call depth. Recursion without a reachable base case can exhaust the stack, and large sums can overflow int. Go does not guarantee tail-call optimization. Choose a loop for straightforward counting.
Try it locally
Write power2(n int) int recursively returning 2 to the power n for 0 <= n <= 10. Base case n == 0 returns 1. Print power2(0), power2(3), power2(5).
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Functions 08: Write a recursive function
Check the lesson objective before moving on.
What is the role of the base case?
Why may a loop be preferable for simple sums?