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 client caching in Go?
How do you set headers in an HTTP response in Go?
How do you handle HTTP client server logging in Go?
Golang Concurrency Best Practices
Golang program for implementation of Bubble Sort
Golang Web Server Example
How do you handle HTTP Client server load balancing in Go?
Golang panic recover example
GO Program to Swap Number Without Using Temporary Variables
Golang program to demonstrates how to encode map data into a JSON string.