Go Tutorials

Go Programs

Go Factorial


Go Factorial

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.


What is Factorial

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.


Syntax

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))
}


Youtube Learning Video



Computing factorial using a loop

We can create a function named factorial to compute the factorial of a given number using a loop.

For example,

  1. Define a function named factorial that takes one parameter n of type int and returns an int.
  2. Initialize a variable result to 1 to store the factorial.
  3. Use a for loop to iterate from 1 to n.
  4. In each iteration, multiply result by the current loop index.
  5. Return the result after the loop completes.
  6. In the main function, define a number, call factorial with the number, and print the result.

Go Program

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))
}

Output

Factorial of 5 is: 120