Does Go language supports recursion?

Learn about the recursion, does Go language supports recursion?
Submitted by IncludeHelp, on October 05, 2021

Let's understand, what is recursion?
In computer science, a recursion function is a function that calls itself during its execution. Recursion functions allow programmers to write efficient programs using a minimal amount of code.

Now coming to the question, does Go language supports recursion?

The answer is – Yes, Go supports recursive functions (recursion).

Consider the below example,

package main

import (
	"fmt"
)

// Recursion function
func fact(n int) int {
	if n == 0 {
		return 1
	}
	return n * fact(n-1)
}

func main() {
	x := 5
	factorial := fact(x)
	fmt.Println("Factorial of", x, "is", factorial)

	x = 15
	factorial = fact(x)
	fmt.Println("Factorial of", x, "is", factorial)
}

Output:

Factorial of 5 is 120
Factorial of 15 is 1307674368000

Golang FAQ »



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.