Golang Program to Find the Factorial of a Given Number Using Recursion


March 8, 2022, Learn eTutorial
1184

For a better understanding of this example, we always recommend you to learn the basic topics of Golang programming listed below:

In this section, we’ll focus our attention to find the factorial of a given number using GO language. So let’s know what Factorial is.

Factorial of a number

The factorial of a given number is the product of all the natural numbers up to the given number. It will be indicated by using an exclamation mark '!'. To understand more details, let us see the below examples.

Factorial of 3 = 3*2*1 = 6

Factorial of 7 = 7*6*5*4*3*2*1 = 5040

How to find the factorial of a given number

In this Go program, we need to find the factorial of a given number by using Recursion. Recursion is a programming technique using a function or algorithm which allows to call itself one or more times until a specified condition is met.

The logic we applied in this GO program is to declare the variable num, Then read the number, which you want to find factorial, from the user and save it into the variable num. Define a function factorial(num)  to calculate the factorial of a number. Here the function accepts the input number num. If the number num is zero or one the factorial will be 1. Otherwise, calculate the factorial By using recursion function as num*function(num-1).

Here we can use the built-in function fmt.scanln() to read the input value. Output can display by using the built-in function fmt.println(). Both built-in functions are defined under the fmt package. In order to use these functions, we should import the “fmt” package into our program.

Given below are the steps which are used in the Go program.

ALGORITHM 

STEP 1: Import the package fmt
STEP 2: Open the main() to start the program, GO program execution starts with the main()
STEP 3: Declare the variables num.
STEP 4: Read the input number num which you want to find factorial.
STEP 5: Call the function factorial(num)
STEP6: Display Factorial of the number on the output screen.
STEP 7: Exit

Steps to Implement factorial(num)

STEP 1: Define a function that accepts the input number num
STEP 2: Check using if the input number num is 1 or zero. if valid, then return 1. Otherwise, return num*function(num-1)
 

Golang Source Code

                                          package main
import "fmt"
func factorial(num int) int{
   if num == 1 || num == 0{
      return num
   }
   return num * factorial(num-1)
}

func main(){
   var num int
   fmt.Println("Enter the number")
   fmt.Scan(#)
   fmt.Println("Factorial of the number is") 
   fmt.Println(factorial(num))
}   
                                      

OUTPUT

Enter the number
7
Factorial of the number is
5040