Sum of Digits in Java Using Recursion

In this blog we will learn how to find sum of given digit using recursion.

Sum of digits using Recursion

Let’s say we want to calculate sum of digit 3456.

winding phase:

sum(3456)= sum(345) + 6

sum(345)= sum(34) + 5

sum(34)=sum(3)+4

sum(3)=3 —-> Base case

Unwinding phase:

sum(3456)= 12 + 6 = 18

sum(345)= 7 + 5

sum(34)=3+4

sum(3)=3

Recursion function:

sum(n)= sum(n/10) + n%10

Base case for recursion here is when we encounter single digit.

If we encounter single digit return that digit

Putting above logic in a program

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
public class Demo {

    public static void main(String[] args) {
        System.out.println( sumOfDigits(2345));
        System.out.println( sumOfDigits(1234));
    }

    public static int sumOfDigits(int n){
        if(n< 10)
            return n;
        return sumOfDigits(n/10) + n  % 10;
    }

}

Output:

1
2
14
10

Sum of digits without Recursion

If you want to calculate sum of given digit without recursion you can use loop to check if the number is not equal to zero.

Within the loop you can perform operations to add last digit to the sum and remove the last digit.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class Demo {

    public static void main(String[] args) {
        int number = 12345;
        int sum = sumDigits(number);
        System.out.println("Sum of digits in " + number + " is: " + sum);

    }

    // Method to sum digits without recursion
    static int sumDigits(int num) {
        int sum = 0;

        // Continue until num becomes 0
        while (num != 0) {
            // Add the last digit to the sum
            sum += num % 10;

            // Remove the last digit
            num /= 10;
        }

        return sum;
    }

}

Output is:

1
Sum of digits in 12345 is: 15