Menu Close

Go – Program to calculate sum of digits in go

Here, we will see program to calculate sum of digits in go. Given below, you can find algorithm and program.

Algorithm:

  • Get the number from user
  • calculate sum of digits
  • Return the result
Input: num = 13
Output: 4

Input: num = 10
Output: 1

Input: num = 321
Output: 6

Code:

package main

import (
  "fmt"
)

func digit_sum(num int) int {

  sum := 0

  for i := num; i > 0; i = i / 10 {

    sum = sum + (i % 10)

  }

  return sum

}

func main() {

  sum := digit_sum(13)

  fmt.Println(sum)

  sum = digit_sum(10)

  fmt.Println(sum)

  sum = digit_sum(321)

  fmt.Println(sum)
}

Output:

4

1

6

To learn more about golang. Please follow given below link.

https://www.techieindoor.com/go-lang/

References:

https://golang.org/doc/
https://golang.org/pkg/
Posted in golang, golang program

Leave a Reply

Your email address will not be published. Required fields are marked *