Saturday 28 May 2016

Find sum of each digit in a number using recursion


Recursion is a technique which allows to define something in terms of itself which means recursion allows a method to call itself repeatedly.Finding sum of digit using for loop is easy but using recursion it is bit tricky.

Sample Program:-


 /**  
  * @author Dixit  
  *  
  */  
 public class SumOfDigitUsingRecursion {  
      private static int sum = 0;  
      /**  
       * @param args  
       */  
      public static void main(String[] args) {  
           String number = "7214";  
           if (number != null && !number.trim().isEmpty())  
                System.out  
                          .println("Sum of Digit of given number " + number  
                                    + " is :-"  
                                    + getSumOfDigit(Integer.parseInt(number.trim())));  
           else  
                System.out.println("Either String is empty or null");  
      }  
      private static int getSumOfDigit(int num) {  
           if (num == 0)  
                return sum;  
           else {  
                sum = sum + (num % 10);  
                getSumOfDigit(num / 10);  
           }  
           return sum;  
      }  
 }  


Limitations:
  • If your number is larger, then it will occupy more memory space as well as time.


Enjoy Programming:)

No comments:

Post a Comment