In this tutorial, we will learn how to compute the factorial of a number using a loop in Go. Factorial of a number is the product of all positive integers less than or equal to that number.
Factorial of a number n
(denoted as n!
) is the product of all positive integers less than or equal to n
. For example, factorial of 5 (5!
) is calculated as 5 * 4 * 3 * 2 * 1 = 120
.
The syntax to compute factorial using a loop in Go is:
package main
import (
"fmt"
)
// factorial computes the factorial of a given number using a loop
func factorial(n int) int {
result := 1
for i := 1; i <= n; i++ {
result *= i
}
return result
}
func main() {
number := 5
fmt.Printf("Factorial of %d is: %d\n", number, factorial(number))
}
We can create a function named factorial
to compute the factorial of a given number using a loop.
For example,
factorial
that takes one parameter n
of type int
and returns an int
.result
to 1 to store the factorial.for
loop to iterate from 1 to n
.result
by the current loop index.result
after the loop completes.factorial
with the number, and print the result.package main
import (
"fmt"
)
// factorial computes the factorial of a given number using a loop
func factorial(n int) int {
result := 1
for i := 1; i <= n; i++ {
result *= i
}
return result
}
func main() {
number := 5
fmt.Printf("Factorial of %d is: %d\n", number, factorial(number))
}
Factorial of 5 is: 120