0
0
GoProgramBeginner · 2 min read

Go Program to Find Sum of Digits of a Number

In Go, you can find the sum of digits of a number by repeatedly extracting the last digit using num % 10, adding it to a sum variable, and then removing the last digit with num /= 10 until the number becomes zero.
📋

Examples

Input123
Output6
Input0
Output0
Input9999
Output36
🧠

How to Think About It

To find the sum of digits, think of the number as a collection of single digits. Extract each digit from the right by using the remainder operator %, add it to a running total, then remove that digit by dividing the number by 10. Repeat until no digits remain.
📐

Algorithm

1
Get the input number.
2
Initialize sum to 0.
3
While the number is greater than 0:
4
Extract the last digit using remainder operator.
5
Add the digit to sum.
6
Remove the last digit by dividing the number by 10.
7
Return the sum.
💻

Code

go
package main

import "fmt"

func main() {
    num := 12345
    sum := 0
    for num > 0 {
        digit := num % 10
        sum += digit
        num /= 10
    }
    fmt.Println(sum)
}
Output
15
🔍

Dry Run

Let's trace the number 123 through the code to find the sum of its digits.

1

Initial values

num = 123, sum = 0

2

First iteration

digit = 123 % 10 = 3, sum = 0 + 3 = 3, num = 123 / 10 = 12

3

Second iteration

digit = 12 % 10 = 2, sum = 3 + 2 = 5, num = 12 / 10 = 1

4

Third iteration

digit = 1 % 10 = 1, sum = 5 + 1 = 6, num = 1 / 10 = 0

5

Loop ends

num is now 0, loop stops, sum = 6

num beforedigit extractedsum afternum after division
1233312
12251
1160
💡

Why This Works

Step 1: Extract last digit

Using num % 10 gets the last digit of the number because it gives the remainder after dividing by 10.

Step 2: Add digit to sum

Add the extracted digit to the running total stored in sum.

Step 3: Remove last digit

Divide the number by 10 using integer division num /= 10 to drop the last digit and move to the next.

🔄

Alternative Approaches

Convert number to string and sum digits
go
package main

import (
    "fmt"
    "strconv"
)

func main() {
    num := 12345
    sum := 0
    strNum := strconv.Itoa(num)
    for _, ch := range strNum {
        digit := int(ch - '0')
        sum += digit
    }
    fmt.Println(sum)
}
This method uses string conversion and is easy to read but slower due to string operations.
Recursive sum of digits
go
package main

import "fmt"

func sumDigits(num int) int {
    if num == 0 {
        return 0
    }
    return num%10 + sumDigits(num/10)
}

func main() {
    fmt.Println(sumDigits(12345))
}
Uses recursion for a clean approach but may cause stack overhead for very large numbers.

Complexity: O(d) time, O(1) space

Time Complexity

The loop runs once for each digit in the number, so time depends on the number of digits, which is O(d).

Space Complexity

Only a few variables are used, so space is constant O(1).

Which Approach is Fastest?

The arithmetic method using modulo and division is fastest and uses least memory compared to string conversion or recursion.

ApproachTimeSpaceBest For
Modulo and DivisionO(d)O(1)Fastest and simplest for numeric input
String ConversionO(d)O(d)Easy to understand, slower for large numbers
RecursionO(d)O(d)Clean code but uses stack memory
💡
Use integer division and modulo to extract digits efficiently without converting to strings.
⚠️
Forgetting to update the number by dividing by 10 causes an infinite loop.