0
0
JavaProgramBeginner · 2 min read

Java Program to Find Sum of Digits

To find the sum of digits in Java, use a loop to extract each digit with num % 10, add it to a sum, and reduce the number by num = num / 10 until it becomes zero.
📋

Examples

Input123
Output6
Input0
Output0
Input9999
Output36
🧠

How to Think About It

To find the sum of digits, think of peeling off the last digit of the number one by one. You get the last digit by using the remainder operator % with 10. Add this digit to a total sum. Then remove the last digit by dividing the number by 10. Repeat until the number is zero.
📐

Algorithm

1
Get the input number.
2
Initialize sum to zero.
3
While the number is greater than zero:
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 or print the sum.
💻

Code

java
public class SumOfDigits {
    public static void main(String[] args) {
        int num = 123;
        int sum = 0;
        while (num > 0) {
            sum += num % 10;
            num /= 10;
        }
        System.out.println("Sum of digits: " + sum);
    }
}
Output
Sum of digits: 6
🔍

Dry Run

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

1

Start

num = 123, sum = 0

2

First loop

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

3

Second loop

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

4

Third loop

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

5

End loop

num is 0, stop loop

numnum % 10sumnum after division
1233312
12251
1160
💡

Why This Works

Step 1: Extract last digit

Using num % 10 gives the last digit of the number.

Step 2: Add digit to sum

Add the extracted digit to the running total sum.

Step 3: Remove last digit

Divide the number by 10 using num /= 10 to remove the last digit.

Step 4: Repeat until done

Continue until the number becomes zero, meaning all digits are processed.

🔄

Alternative Approaches

Recursive method
java
public class SumOfDigits {
    public static int sumDigits(int num) {
        if (num == 0) return 0;
        return num % 10 + sumDigits(num / 10);
    }
    public static void main(String[] args) {
        int num = 123;
        System.out.println("Sum of digits: " + sumDigits(num));
    }
}
Uses recursion to sum digits; elegant but uses call stack.
Convert to String
java
public class SumOfDigits {
    public static void main(String[] args) {
        int num = 123;
        String str = Integer.toString(num);
        int sum = 0;
        for (char c : str.toCharArray()) {
            sum += c - '0';
        }
        System.out.println("Sum of digits: " + sum);
    }
}
Converts number to string and sums digits; easy to read but less efficient.

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

Time Complexity

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

Space Complexity

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

Which Approach is Fastest?

The iterative method is fastest and uses least memory; recursion adds call stack overhead; string conversion is less efficient.

ApproachTimeSpaceBest For
Iterative (mod/div)O(d)O(1)Fastest and simplest
RecursiveO(d)O(d)Elegant but uses stack
String conversionO(d)O(d)Easy to read, less efficient
💡
Use num % 10 to get the last digit and num /= 10 to remove it.
⚠️
Forgetting to update the number by dividing by 10 causes an infinite loop.