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)
}
- Define a function
sumOfDigits
that takes an integer n
as input and returns an integer. - Initialize a variable
sum
to store the sum of digits and set it to 0. - Start a
for
loop that continues until n
is not equal to 0. - Inside the loop:
- Add the last digit of
n
to the sum
variable using the modulus operator (n % 10
). This extracts the last digit of n
. - Divide
n
by 10 (n /= 10
) to remove the last digit and update n
with the remaining digits. - Return the
sum
of digits. - In the
main
function: - Define a variable
number
and assign it an integer value (e.g., 12345). - Call the
sumOfDigits
function with number
as an argument and store the result in the result
variable. - Print the sum of digits using
fmt.Printf
.