Given a number the task is to calculate the sum of the digits using recursion.
Example: Let us take a number 3412. Here sum of digits is 3+4+1+2 = 10.
Java
import java.util.*;
public class SumDigitsRec
{
public int getSum(int n)
{
if(n==0)
{
return 0;
}
else
{
return (n%10)+getSum(n/10);
}
}
public static void main(String args[])
{
int n=0,sum=0;
Scanner sc=new Scanner(System.in);
SumDigitsRec ob=new SumDigitsRec();
System.out.print("Enter a number: ");
n=sc.nextInt();
sum=ob.getSum(n);
System.out.println("Sum of the digits: "+sum);
}
}Java