Search⌘ K
AI Features

Recursion vs. Iteration

Explore the differences between recursion and iteration by solving the same problem using both methods in Go. Understand when to choose recursion for naturally hierarchical problems and iteration for efficiency and simplicity. Learn about memory usage, speed, and readability trade-offs to make informed coding decisions.

We'll cover the following...

In the previous lesson, recursion was introduced as a technique where a function calls itself with a smaller input until it reaches a base case. This raises an important question: if loops can already handle repetition, what advantages does recursion provide? Conversely, why is recursion not always the preferred approach?

The answer is that recursion and iteration are two different tools, and knowing when to reach for each one is an important skill. In this lesson, we will solve the same problem both ways in Go, compare the two approaches, and build an intuition for when each one is the right choice.

Two ways to solve the same problem

Let's use factorial again as we are already familiar with it. Recall that 5! = 5 × 4 × 3 × 2 × 1 = 120.

Iterative approach

An iterative solution uses a for loop to multiply the numbers together one by one, building up the result step by step.

Python 3.14.0
package main
import "fmt"
func factorialIterative(n int) int {
result := 1
for i := 1; i <= n; i++ {
result *= i
}
return result
}
func main() {
fmt.Println(factorialIterative(5)) // Output: 120
fmt.Println(factorialIterative(3)) // Output: 6
fmt.Println(factorialIterative(0)) // Output: 1
}
...