I'm trying to create a small program that allows a user to input an integer which will output the product such as follows:
For example:
a = 5, 5*4*3*2 = 120
a = 4, 4*3*2*1 = 24
a = 3, 3*2*1 = 6
Can someone provide guidance as I'm stuck on how to frame this more efficiently. If using Python, I would probably write the logic something like:
def a(num):
x = 1
for i in range (num):
x=x*(i + 1)
return x
print a(5)
You need to learn about the go language itself first, after that you'll be able to convert your python code into go, easily.
Few go learning resources:
But anyway, here is the go version of your python code:
func a(num int) int {
x := 1
for i := 0; i < num; i++ {
x = x * (i + 1)
}
return x
}
func main() {
fmt.Println(a(5)) // 120
fmt.Println(a(4)) // 24
fmt.Println(a(3)) // 6
}
Working playground: https://play.golang.org/p/glHwuMhTDYj
the main function taken from previous answer - only the scanf added here as you requested
package main
import (
"fmt"
)
func a(num int) int {
x := 1
for i := 0; i < num; i++ {
x = x * (i + 1)
}
return x
}
func main() {
var i int
_, err := fmt.Scanf("%d", &i)
if nil == err {
fmt.Println(a(i))
} else {
panic(err)
}
}