go sum of digits in an integer

package main

import (
    "fmt"
)

func sumOfDigits(n int) int {
    sum := 0
    for n != 0 {
        sum += n % 10
        n /= 10
    }
    return sum
}

func main() {
    number := 12345
    result := sumOfDigits(number)
    fmt.Printf("Sum of digits of %d is: %d\n", number, result)
}
  1. Define a function sumOfDigits that takes an integer n as input and returns an integer.
  2. Initialize a variable sum to store the sum of digits and set it to 0.
  3. Start a for loop that continues until n is not equal to 0.
  4. Inside the loop:
  5. Add the last digit of n to the sum variable using the modulus operator (n % 10). This extracts the last digit of n.
  6. Divide n by 10 (n /= 10) to remove the last digit and update n with the remaining digits.
  7. Return the sum of digits.
  8. In the main function:
  9. Define a variable number and assign it an integer value (e.g., 12345).
  10. Call the sumOfDigits function with number as an argument and store the result in the result variable.
  11. Print the sum of digits using fmt.Printf.