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

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 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




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.