Write a Go Program to Find factorial of a Number using For loop. The for loop (for i := 1; i <= factorialnum; i++) iteration starts at one and ends at user given value. Within the loop (factorial = factorial * i), we multiply each value with a factorial variable value.
package main import "fmt" func main() { var factorialnum, factorial int factorial = 1 fmt.Print("Enter any Number to find the Factorial = ") fmt.Scanln(&factorialnum) for i := 1; i <= factorialnum; i++ { factorial = factorial * i } fmt.Println("The Factorial of ", factorialnum, " = ", factorial) }
Go Program to Find factorial of a Number using Functions
In this Go example, we created a separate function (calcFactorial (factorialnum int)) that returns the factorial of the user given number.
package main import "fmt" var factorial int func calcFactorial(factorialnum int) int { factorial = 1 for i := 1; i <= factorialnum; i++ { factorial = factorial * i } return factorial } func main() { var factorialnum int fmt.Print("Enter any Number to find the Factorial = ") fmt.Scanln(&factorialnum) factorial = calcFactorial(factorialnum) fmt.Println("The Factorial of ", factorialnum, " = ", factorial) }
Enter any Number to find the Factorial = 9
The Factorial of 9 = 362880
In this Golang program, we created a recursive function that returns the factorial of a number.
package main import "fmt" var factorial int func calcFactorial(factorialnum int) int { if factorialnum == 0 || factorialnum == 1 { return 1 } else { return factorialnum * calcFactorial(factorialnum-1) } } func main() { var factorialnum int fmt.Print("Enter any Number to find the Factorial = ") fmt.Scanln(&factorialnum) factorial = calcFactorial(factorialnum) fmt.Println("The Factorial of ", factorialnum, " = ", factorial) }
Enter any Number to find the Factorial = 4
The Factorial of 4 = 24
Go factorial of a Number program using Pointers.
package main import "fmt" func main() { var factorialnum, factorial int var nw *int factorial = 1 fmt.Print("Enter any Number to find the Factorial = ") fmt.Scanln(&factorialnum) nw = &factorialnum for i := 1; i <= *nw; i++ { factorial = factorial * i } fmt.Println("The Factorial of ", factorialnum, " using Normal = ", factorial) fmt.Println("The Factorial of ", *nw, " using Pointers = ", factorial) }
Enter any Number to find the Factorial = 6
The Factorial of 6 using Normal = 720
The Factorial of 6 using Pointers = 720
Golang Factorial of a Number example using Call by Reference.
package main import "fmt" var factorial int func calcFactorial(factnum *int) int { factorial = 1 for i := 1; i <= *factnum; i++ { factorial = factorial * i } return factorial } func main() { var factorialnum int fmt.Print("Enter any Number to find the Factorial = ") fmt.Scanln(&factorialnum) factorial = calcFactorial(&factorialnum) fmt.Println("The Factorial of ", factorialnum, " = ", factorial) }
Enter any Number to find the Factorial = 7
The Factorial of 7 = 5040