- class Sum
- {
- int sum =0;
- int addDigit(int num)
- {
- if( num == 0)
- return 0;
- sum = num%10 + addDigit(num/10);
- return sum;
- }
- }
- class SumRecursive
- {
- public static void main(String []a)
- {
- Sum s = new Sum();
- int num;
- System.out.println("Enter the number:");
- num = Integer.parseInt(System.console().readLine());
- int output= s.addDigit(num);
- System.out.println("Sum of digits in the given number is:"+ output);
- }
- }
Output: |
---|
Enter the number: |
2345 |
Sum of digits in the given number is:14 |