Go Recursive Function

1. Introduction

Recursion is a fundamental programming technique where a function calls itself to solve a problem. In Go, recursion can be implemented just like in other programming languages, allowing functions to be defined in terms of themselves. This post will demonstrate a recursive function in Go by implementing the classic example of calculating the factorial of a number.

Definition

A recursive function in Go is a function that calls itself during its execution. To prevent infinite recursion, a base case is defined for which the function does not recurse. Therefore, each recursive call should progress towards this base case.

2. Program Steps

1. Define a recursive function that calculates the factorial of a number.

2. Implement the base case to return 1 when the function is called with 0 or 1.

3. For all other cases, the function should call itself with a decremented value.

4. Define the main function which serves as the entry point of the program.

5. Within main, call the recursive factorial function and print its result.

3. Code Program

package main

import "fmt"

// factorial recursively calculates the factorial of n.
func factorial(n uint) uint {
	if n == 0 || n == 1 {
		return 1 // Base case: factorial of 0 or 1 is 1
	}
	// Recursive case: n * factorial of (n-1)
	return n * factorial(n-1)
}

func main() {
	// Calculate the factorial of 5
	result := factorial(5)
	fmt.Printf("The factorial of 5 is %d\n", result)
}

Output:

The factorial of 5 is 120

Explanation:

1. package main indicates the program's package name.

2. import "fmt" is used to import the Format package for formatted I/O.

3. factorial is a function that takes an unsigned integer n and returns an unsigned integer. This signature ensures that only non-negative numbers are factored, avoiding negative recursion.

4. The function checks if n is 0 or 1, which are the base cases, and returns 1 if so.

5. If n is greater than 1, factorial calls itself with n-1. This is the recursive step that eventually reaches the base case.

6. The main function calls factorial with 5 and assigns the result to result.

7. fmt.Printf is then used to print the result to the console, showing that the factorial of 5 is 120.


Comments