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
GO Program to Generate Multiplication Table
GO language program with example of String Compare function
Program in Go language to print Floyd's Triangle
Program in Golang to print Pyramid of Numbers
Program in Go language to Program to Add Two Matrix Using Multi-dimensional Arrays
GO Program to Swap Number Without Using Temporary Variables