GO Program to Find Factorial of a Number
This program takes a positive integer from the user and computes factorial using for loop. New function factorial created which returns the factorial value of a number.
Example
//Program to find Factorial of number
package main
import "fmt"
/* Variable Declaration */
var factVal uint64 = 1 // uint64 is the set of all unsigned 64-bit integers.
// Range: 0 through 18446744073709551615.
var i int = 1
var n int
/* function declaration */
func factorial(n int) uint64 {
if(n < 0){
fmt.Print("Factorial of negative number doesn't exist.")
}else{
for i:=1; i<=n; i++ {
factVal *= uint64(i) // mismatched types int64 and int
}
}
return factVal /* return from function*/
}
func main(){
fmt.Print("Enter a positive integer between 0 - 50 : ")
fmt.Scan(&n)
fmt.Print("Factorial is: ",factorial(n))
}
factVal *= uint64(i) // i is int and factVal is uint64. Compiler will through exception "mismatched types int64 and int" if we not convert i to uint64.
Most Helpful This Week
How do you handle HTTP authentication with an HTTP client in Go?
How to check if an item exists in Slice in Golang?
How do you handle HTTP redirects in Go?
Web Application to generate QR code in Golang
Implementing Multiple Interfaces in Go Programming Language
Concurrently printing array elements using goroutines and channels