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 Fibonacci Sequence Up to a Certain Number
Contains, ContainsAny, Count and EqualFold string functions in Go Language
GO Program to Generate Multiplication Table
GO Program to Check Armstrong Number
Program in Go language to Calculate Average Using Arrays
GO language program with example of Array Reverse Sort Functions for integer and strings