0
0
JavaProgramBeginner · 2 min read

Java Program for Sum of Digits Using Recursion

You can find the sum of digits of a number in Java using recursion by defining a method like int sumOfDigits(int n) { if (n == 0) return 0; return n % 10 + sumOfDigits(n / 10); } which adds the last digit to the sum of the remaining digits recursively.
📋

Examples

Input123
Output6
Input0
Output0
Input9999
Output36
🧠

How to Think About It

To find the sum of digits using recursion, think of the number as made of its last digit plus the rest. Use n % 10 to get the last digit and n / 10 to remove it. Keep adding the last digit to the sum of the remaining digits until the number becomes zero.
📐

Algorithm

1
Check if the number is zero; if yes, return zero as the sum.
2
Find the last digit of the number using modulus 10.
3
Call the function recursively with the number divided by 10 (removing the last digit).
4
Add the last digit to the result of the recursive call.
5
Return the total sum.
💻

Code

java
public class SumOfDigits {
    public static int sumOfDigits(int n) {
        if (n == 0) {
            return 0;
        }
        return n % 10 + sumOfDigits(n / 10);
    }

    public static void main(String[] args) {
        int number = 123;
        System.out.println("Sum of digits of " + number + " is " + sumOfDigits(number));
    }
}
Output
Sum of digits of 123 is 6
🔍

Dry Run

Let's trace the number 123 through the recursive sumOfDigits method.

1

Initial call

sumOfDigits(123) calls sumOfDigits(12) and adds 3 (123 % 10)

2

Second call

sumOfDigits(12) calls sumOfDigits(1) and adds 2 (12 % 10)

3

Third call

sumOfDigits(1) calls sumOfDigits(0) and adds 1 (1 % 10)

4

Base case

sumOfDigits(0) returns 0

5

Return values

sumOfDigits(1) returns 1 + 0 = 1 sumOfDigits(12) returns 2 + 1 = 3 sumOfDigits(123) returns 3 + 3 = 6

Callnn % 10Recursive call with n/10Return value
sumOfDigits(123)1233sumOfDigits(12)6
sumOfDigits(12)122sumOfDigits(1)3
sumOfDigits(1)11sumOfDigits(0)1
sumOfDigits(0)00base case0
💡

Why This Works

Step 1: Base case stops recursion

When the number becomes zero, the function returns 0 to stop further recursive calls.

Step 2: Extract last digit

Using n % 10 extracts the last digit of the current number.

Step 3: Recursive call reduces problem size

Calling the function with n / 10 removes the last digit, making the problem smaller each time.

Step 4: Sum builds up on return

Each recursive call returns the sum of digits found so far, adding the last digit at each step.

🔄

Alternative Approaches

Iterative approach
java
public class SumOfDigits {
    public static int sumOfDigits(int n) {
        int sum = 0;
        while (n != 0) {
            sum += n % 10;
            n /= 10;
        }
        return sum;
    }

    public static void main(String[] args) {
        int number = 123;
        System.out.println("Sum of digits of " + number + " is " + sumOfDigits(number));
    }
}
Uses a loop instead of recursion; easier to understand for some but less elegant.
String conversion approach
java
public class SumOfDigits {
    public static int sumOfDigits(int n) {
        String s = Integer.toString(n);
        int sum = 0;
        for (char c : s.toCharArray()) {
            sum += c - '0';
        }
        return sum;
    }

    public static void main(String[] args) {
        int number = 123;
        System.out.println("Sum of digits of " + number + " is " + sumOfDigits(number));
    }
}
Converts number to string and sums digits; less efficient but simple to read.

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

Time Complexity

The function calls itself once per digit, so time grows linearly with the number of digits d.

Space Complexity

Each recursive call adds a layer to the call stack, so space also grows linearly with d.

Which Approach is Fastest?

The iterative method uses constant space and is faster in practice, but recursion is elegant and easy to understand.

ApproachTimeSpaceBest For
RecursiveO(d)O(d)Learning recursion and elegant code
IterativeO(d)O(1)Performance and memory efficiency
String conversionO(d)O(d)Simple code but less efficient
💡
Always include a base case in recursion to avoid infinite calls.
⚠️
Forgetting to reduce the number in the recursive call causes infinite recursion.