Go Language Tutorial
This go program is used to find the sum of digits for a number which is provided as user input using for loop.
package main import "fmt" func sumOfDigits(num int) int { var sum int = 0 for temp:=num; temp!=0; temp=temp/10 { remainder := temp % 10 sum = sum + remainder } return sum } func main() { var num, digits_sum int digits_sum = 0 fmt.Print("Enter number: ") fmt.Scanf("%d", &num) digits_sum = sumOfDigits(num) fmt.Printf("Sum of digits %d: %d\n", num, digits_sum) }Output:
$ go build digits-sum.go $ ./digits-sum Enter number: 345 Sum of digits 345: 12 $ ./digits-sum Enter number: 3456 Sum of digits 3456: 18
Note: when providing the negative number to find the sum of digits to this go program and negative sign is added with the sum of digits.
$ ./digits-sum Enter number: -76 Sum of digits -76: -13
This go program is used to find the product of digits for a number which is provided as user input using for loop.
package main import "fmt" func productOfDigits(num int) int { var product int = 1 for temp:=num; temp!=0; temp=temp/10 { remainder := temp % 10 product = product * remainder } return product } func main() { var num, digits_product int digits_product = 0 fmt.Print("Enter number: ") fmt.Scanf("%d", &num) digits_product = productOfDigits(num) fmt.Printf("Product of digits %d: %d\n", num, digits_product) }Output:
$ go build digits-product.go $ ./digits-product Enter number: 345 Product of digits 345: 60 $ ./digits-product Enter number: 4353 Product of digits 4353: 180
Note: when providing the negative number to find the product of digits to this go program and negative sign is added with the product of digits.
$ ./digits-product Enter number: -345 Product of digits -345: -60 $ ./digits-product Enter number: -908 Product of digits -908: 0