Sum of Digits in recursion

The “Sum of Digits in recursion” in Java refers to solving the problem of finding the sum of digits of a number using a recursive method.

For example, if the number is 1234, the sum of digits is: 1+2+3+4=101 + 2 + 3 + 4 = 10


How recursion works here:

  1. Base case: If the number becomes 0, return 0.
  2. Recursive case: Take the last digit using n % 10, and add it to the recursive result of the remaining number (n / 10).

Example Code in Java:

public class SumOfDigits {
    // Recursive function to find sum of digits
    public static int sumOfDigits(int n) {
        // Base case
        if (n == 0) {
            return 0;
        }
        // Recursive step: last digit + sum of remaining digits
        return (n % 10) + sumOfDigits(n / 10);
    }

    public static void main(String[] args) {
        int number = 1234;
        int result = sumOfDigits(number);
        System.out.println("Sum of digits of " + number + " is: " + result);
    }
}

Output:

Sum of digits of 1234 is: 10

This program keeps breaking the number down until it reaches 0, then adds the digits back together during the recursion return phase.

Leave a Reply