Recursion is an algorithm in which one of the steps invokes the currently running method or function. This algorithm acquires the outcome for the input by applying basic tasks and then returns the value.
A recursion algorithm is implemented in the following code snippet. The Factor() method takes the num as a parameter and returns the factorial of num. The method uses recursion to calculate the factorial of the number:
package main// importing fmt and bytes packageimport ("fmt")//factorial methodfunc Factor(num int) int {if num<= 1 {return 1}return num * Factor(num-1)}//main methodfunc main() {var num int = 5fmt.Printf("Factorial: %d is %d", num, Factor(num))}Output:
Factorial: 5 is 120
DSAGo
Comments
Post a Comment