 Go Language Tutorial

# Go Program to Calculate Factorial Value

## Go Program to Calculate Factorial Value of a Number

This go program is used to find the factorial value for a number which is provided by user input.

## Factorial Algorithm

```Factorial of a Number = 1*2* .... (Number-1)*Number.
```

## Go Programming Example to Calculate Factorial Value using Recursion

Recursive function is a function which calls itself.

This go program is used to find the factorial value using recursive function.

```package main

import "fmt"

func factorial(num int) int {
if num > 1 {
return (num * factorial(num-1))
} else {
return 1
}
}

func main() {
var num, factorial_val  int
factorial_val = 1
fmt.Print("Enter number: ")
fmt.Scanf("%d", &num)

if num  < 0 {
fmt.Println("\nError - negative number!")
} else {
factorial_val = factorial(num)
fmt.Printf("Factorial of %d: %d\n", num, factorial_val)
}
}
```
Output:
```]\$ go build factorial.go
\$ ./factorial
Enter number: 6
Factorial of 6: 720
\$ ./factorial
Enter number: -1

Error - negative number!
```

## Go Programming Example to Calculate Factorial Value using for loop

This go program is used to calculate the factorial value for a number which is provided as user input. and also uses for loop to compute the factorial value.

```package main

import "fmt"

func factorial(num int) int {
var fact_val = 1
for i:=1;i<=num;i++ {
fact_val = fact_val * i
}
return fact_val
}

func main() {
var num, factorial_val  int
factorial_val = 1
fmt.Print("Enter number: ")
fmt.Scanf("%d", &num)

if num  < 0 {
fmt.Println("\nError - negative number!")
} else {
factorial_val = factorial(num)
fmt.Printf("Factorial of %d: %d\n", num, factorial_val)
}
}
```
Output:
```]\$ go build factorial.go
\$ ./factorial
Enter number: 4
Factorial of 4: 24
\$ ./factorial
Enter number: -6

Error - negative number!
```