Go Recursion
Go Language - Recursion
The process of repeating items in a similar way is known as recursion. Calling a function inside the same function is called recursive function call.
Syntax
func recurs(){
recurs() /* function calls itself */
}
func main(){
recurs() /* Calling recurs()*/
}
Go programming allows a program to call itself. Here the programmers need to be careful where define the exit condition from the function, otherwise it will become infinite loop.
This recursive functions are helpful in solving many mathematical problems such as Fibonacci series, factorial of a number, etc.
Example (Factorial of a number using recursion) :
CODE/PROGRAM/EXAMPLE
package main
import"fmt"
func factorial(i int)int{
if(i <=1){
return1
}
return i *factorial(i -1)
}
func main(){
vari int=15
fmt.Printf("Factorial of the number %d is %d",i,factorial(i))
}
Output :
Factorial of the number 7 is 5040
Example (Fibonacci series using recursion) :
CODE/PROGRAM/EXAMPLE
package main
import"fmt"
func fibonaci(i int)(ret int){
if i ==0{
return 0}
if i ==1{
return 1
}
return fibonaci(i-1)+fibonaci(i-2)
}
func main(){
var i int
for i =0;i <9;i++{
fmt.Printf("%d ",fibonaci(i))
}
}
Output :
0 1 1 2 3 5 8 13 21