Use cases of recursion in GoLang

  • date 1st May, 2021 |
  • by Prwatech |
  • 0 Comments

Recursion is a concept to calling a function within a function itself.

Use Case 1:

Finite Recursion :  In finite function , the function stops at a finite number of steps.

Program – To print fibonacci series

package main

import "fmt"

func fib(i int) int {

            if i == 0 {

                        return 0

            }

            if i == 1 {

                        return 1

            }

            return fib(i-1) + fib(i-2)

}

func main() {

            var i int

            for i = 0; i< 10; i++ {

                        fmt.Printf(" %d  ", fib(i))

            }

}

Output :

Use Case 2:

Program to print numbers by recursive function.

package main

import (

            "fmt"

)

funcprintnum(n int) {

            if n > 0 {

                        printnum(n - 1)

                        fmt.Println(n)

            }

}

func main() {

            printnum(5)

}

Output :

Use Case 3:

Infinte Recursion : In infinite recursion the function doesn’t stop calling itself, it runs infinite times.

package main

import (

    "fmt"

)

func rec(){

fmt.Println("Endless")

    rec()

}

func main() { 

}

Output :

Quick Support

image image