Go – Factorial Program using For Loop
In this tutorial, we will write a program to compute factorial of a number using for loop.
In the following program, we write a function factorial
, that takes an integer n
and returns the factorial of this integer. If n is zero, return 1, else, iterate using for loop from 1
to n
, compute the factorial and return the result
.
example.go
</>
Copy
package main
import "fmt"
func factorial(n int) int {
if n == 0 {
return 1
}
result := 1
for i := 1; i <= n; i++ {
result *= i
}
return result
}
func main() {
n := 5
result := factorial(n)
fmt.Println("Factorial of", n, "is :", result)
}
Output
Factorial of 5 is : 120
Conclusion
In this Golang Tutorial, we learned how to write a Go program to compute factorial of a number using for loop.