What is recursion?
Recursion is an algorithm that calls itself on an ever reducing/simplifying version of itself/its dataset.
At its core, a recursive algorithm consists of:
- the base case (the exit condition)
- recursive case (the condition that keeps simplifying the dataset)
Example
Counting down from n while reducing n on each recursive call.
start = 10
countDown = func(n) {
// If we've reached our target n, exit i.e. the base case
if n < 0 {
return
}
println(n)
// Reduce/simplify the dataset i.e. the recursive case
countDown(n-1)
}
countDown(10)
And in Go:
| |