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

February 21, 2022, Learn eTutorial

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

In this program, we will learn to calculate the factorial of a number without using the recursion function. We know the recursion function is the function that can call itself. But in this program, we do this calculation by using a loop instead of a recursion function. Before that here briefly explain what Factorial is. 

We can say 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 '!'. Bellow shows some examples for factorial.  

Factorial of 4 = 4*3*2*1 = 24
Factorial of 5 = 5*4*3*2*1 = 120

In this section, we’ll focus our attention to find the factorial of a given number without using recursion. 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.

In this GO program declare the variable 'i, num, and fact' and read the input number from the user by using the built-in function fmt.println() and fmt.scanln(). Save input value into the variable num. Check if the number is less than or equal to zero. If so, factorial will be 1 otherwise iterate the loop by checking loop condition i<= num.  In each iteration, calculate fact = fact * i. Finally, the result is stored in the variable fact. Display the factorial of the number on the screen.

Given below are the steps to implement factorial in the Go program


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 and fact.
STEP 4: Read the input number num which you want to find factorial.
STEP 5: Check if the number is less than or equal to zero. If so, set 'fact=1' and do step 7. Else do step 6.
STEP 6: By using the for loop with the condition "i<=num", calculate factorial fact=fact*i. Here increment the value of 'i' by 1 in each iteration.
STEP 7: Display Factorial of the number num as fact.
STEP 8: Exit

Golang Source Code

                                          package main
import "fmt"
func main(){
var num, fact int
fmt.Println ("Enter the number")
if num <= 0 {
    fact = 1;
 fact = 1
for i := 1; i <= num; i++ {
        fact = fact * i

fmt.Println ("Factorial of",num ,"=", fact)
} /* End of main() */



Enter the number
Factorial of 5 = 120