Introducing Radical.sh

Forget Code launches a powerful code generator for building API's

Sum of integers in the given number using recursive method in Java

  1. class Sum
  2. {
  3. int sum =0;
  4. int addDigit(int num)
  5. {
  6. if( num == 0)
  7. return 0;
  8. sum = num%10 + addDigit(num/10);
  9. return sum;
  10. }
  11. }
  12. class SumRecursive
  13. {
  14. public static void main(String []a)
  15. {
  16. Sum s = new Sum();
  17. int num;
  18. System.out.println("Enter the number:");
  19. num = Integer.parseInt(System.console().readLine());
  20. int output= s.addDigit(num);
  21. System.out.println("Sum of digits in the given number is:"+ output);
  22. }
  23. }


Output:
Enter the number:
2345
Sum of digits in the given number is:14