Showing posts with label Sum of digits in number using recursion in java. Show all posts
Showing posts with label Sum of digits in number using recursion in java. Show all posts

Monday, 11 June 2018

Sum of digits in number using recursion in java



Sample Program:-


public class SampleProgram {  
      static int sum = 0;  
      public static void main(String[] args) {  
           int number = 1234;  
           System.out.println("sum of digits : " + sumOfDigits(number));  
      }  
      private static int sumOfDigits(int number) {  
           if (number == 0) {  
                return sum;  
           } else {  
                sum = sum + (number % 10);  
                sumOfDigits(number / 10);  
           }  
           return sum;  
      }  
 }  

Output:-


 sum of digits : 10  

Enjoy Coding.