Wednesday, September 20, 2023

Java Program to Find Sum of Digits in a Number using Recursion? Example

Recently this question to ask was one of my readers, which inspired me to write this tutorial. There was a usual check to solve this problem using both recursion and iteration. To be frank, calculating the sum of digits of an integral number is not difficult, but I have still seen quite a few programmers fumbles, even after providing hints in terms of division and modulus operator. The key point here is to know how to use division and modulus operators in Java. This kind of exercise including reversing a number, where you need to find digits from a number, use division operator to remove right, and use modulus operator or % to get rightmost digits.

For example, if you have number 1234 then 1234/10 will give you 123 i.e. rightmost digit 4 is removed, while 1234%10 will give you 4, which is the rightmost digit in that number. 

This is one of the important technique which is used to solve many coding problems like reverse an integer and check if the given number is  palindrome or not. 

If you know this property, you can easily solve lots of problems that are related to reversing numbers e.g. checking if a number is palindrome or finding Armstrong numbers in Java. 



Java program to calculate the sum of digits in a number

How to find sum of digit of a number coding question in JavaHere is a complete Java code example to find the sum of digits using recursion in Java. This Java example also includes an iterative solution to this problem to prepare follow-up questions from the Interviewer. 



By the way, you can also use this example to learn Recursion in Java. It’s a tricky concept, and examples like this certainly help to understand and apply recursion better.

/**
 * Java program to calculate sum of digits for a number using recursion and iteration.
 * Iterative solution uses while loop here.
 *
 * @author Javin Paul
 */
public class SumOfDigit {
 
    public static void main(String args[]) {
      
      System.out.println( "Sum of digit using recursion for number 123 is " 
                           + sumOfDigits(123));
      System.out.println( "Sum of digit using recursion for number 1234 is " 
                           + sumOfDigits(1234));
      System.out.println( "Sum of digit from recursive function for number 321 is " 
                           + sumOfDigits(321));
      System.out.println( "Sum of digit from recursive method for number 1 is " 
                           + sumOfDigits(1));
     
      System.out.println( "Sum of digit using Iteration for number 123 is " 
                           + sumOfDigitsIterative(123));
      System.out.println( "Sum of digit using while loop for number 1234 is "
                           + sumOfDigitsIterative(1234));
     
    } 
   
   
  
    public static int sumOfDigits(int number){
        if(number/10 == 0) return number;
       
        return number%10 + sumOfDigits(number/10);
    }
   
    public static int sumOfDigitsIterative(int number){
        int result  = 0;
        while(number != 0){
            result = result + number%10;
            number = number/10;
        }
       
        return result;
    }
  
}

Output:
Sum of digit using recursion for number 123 is 6
Sum of digit using recursion for number 1234 is 10
Sum of digit from recursive function for number 321 is 6
Sum of digit from recursive method for number 1 is 1
Sum of digit using Iteration for number 123 is 6
Sum of digit using while loop for number 1234 is 10

That's all on How to find the sum of digits of a number using recursion in Java. You should be able to write this method using both Iteration i.e. using loops, and using Recursion i.e. without using loops in Java.

And now is the quiz time, What is the time complexity of this algorithm to find the sum of digits in a given integer number? can you improve this by using any data structure or different approach?

4 comments:

  1. I may do it in this way, it's easier for me to understand,
    public static int sumOfDigits(int digit)
    {
    int re = 0;
    while(digit != 0)
    {
    re += digit%10;
    digit /= 10;
    }
    return re;
    }

    ReplyDelete
  2. Sum of digits os the addition of the digits present in the program.you can get the code from http://letusprogram.wordpress.com/2013/07/12/sum-of-digits-in-java/

    ReplyDelete
  3. there is a bug in first function

    public int getSumOfDigits(int num) {
    // here num is 0 , you dont need to do num/10 , its already coming as num/10
    if (num == 0) return 0;
    return getSumOfDigits(num / 10) + num % 10;
    }

    ReplyDelete
  4. Hello Ansul, do you hava testcase to expose that bug? what about "1" ? 1/10 is also zero so I think the function is Ok as base case is passing 1? No?

    ReplyDelete