×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang program to demonstrate the recursion

Here, we are going to demonstrate the recursion in Golang (Go Language).
Submitted by Nidhi, on March 11, 2021 [Last updated : March 03, 2023]

Recursion Example in Golang

Problem Solution:

In this program, we will create a user-defined function to print numbers from 5 to 1 using a recursive function call. A function call itself is known as a recursive function call.

Program/Source Code:

The source code to demonstrate the recursion is given below. The given program is compiled and executed successfully.

Golang code to demonstrate the example of recursion

// Golang program to demonstrate recursion

package main

import "fmt"

func RecursiveFun(num int) int {
	if num == 0 {
		return num
	} else {
		fmt.Printf("%d ", num)
	}
	num = num - 1
	return RecursiveFun(num)
}

func main() {
	RecursiveFun(5)
}

Output:

5 4 3 2 1

Explanation:

In the above program, we declare the package main. The main package is used to tell the Go language compiler that the package must be compiled and produced the executable file. Here, we imported the fmt package that includes the files of package fmt then we can use a function related to the fmt package.

func RecursiveFun(num int)int{
  if(num==0){
    return num
  }else{
    fmt.Printf("%d ",num)  
  }
  num=num-1
  return RecursiveFun(num)
}

In the above code, we implemented a recursive function RecursiveFun() that accepts an integer number as an argument and prints numbers till 1 using a recursive function call.

In the main() function, we called RecursiveFun() function to print numbers from 5 to 1 on the console screen.

Golang Recursion Programs »





Comments and Discussions!

Load comments ↻





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