Introduction

Hello, fellow explorer! Today, we will unravel the mystery of Recursion — a concept as enthralling as the patterns formed by two mirrors facing each other. Our aim is to decipher recursion, understand its inner workings, and master its application in Go.

Understanding Recursion

Consider a stack of books. Do you want the bottom one? You'll need to remove each book above it, one by one. It's a recurring action — an example of recursion. In programming, recursion involves a function calling itself repeatedly until a specific condition is met, similar to descending stairs one step at a time until you reach the ground.

Here's a simple Go function illustrating recursion:

package main

import "fmt"

func RecursiveFunction(x int) {
    if x <= 0 { // Termination condition --> base case
        fmt.Println("Base case reached")
    } else {
        fmt.Println(x)
        RecursiveFunction(x - 1) // Recursive function call --> recursive case
    }
}

func main() {
    RecursiveFunction(5)
}
/*Output:
5
4
3
2
1
Base case reached
*/

This function keeps calling itself with x getting lower by one until x <= 0, which is our base case. At this point, it stops the recursion.

Defining the Base Case

The base case acts like a friendly signpost, telling the recursion when to stop. In our book stack example, reaching a point where no more books are left to remove serves as the signal. Similarly, x <= 0 is our base case in our function. The base case is crucial as it prevents infinite recursion and related errors.

Defining the Recursive Case

The recursive case is an essential part of recursion — the rule responsible for creating smaller versions of the original problem. Each call brings us a step closer to the base case. Let's use the process of calculating a factorial as an illustrative example.

To find a factorial, we multiply a number by the factorial of the number minus one, and repeat this process until we get to one (our base case):

package main

import "fmt"

func Factorial(n int) int {
    if n == 1 || n == 0 { // base case
        return 1
    } else {
        return n * Factorial(n - 1) // recursive case
    }
}

func main() {
    fmt.Println(Factorial(3)) // we expect 6 (3 * 2 * 1)
}

In this case, when we call Factorial(3), it returns 3 * Factorial(2), where Factorial(2) returns 2 * Factorial(1). As Factorial(1) is a base case, it returns 1. Consequently, the whole recursion chain returns 3 * 2 * 1.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal