Programming Examples
Java recursive function to find the sumofdigit
Write a Java Program to create recursive function to find the sum of digits of given number.
import java.util.*;
class SumOfDigit
{
int sod(int n)
{
if(n==0)
{
return 0;
}
else
{
return n%10+sod(n/10);
}
}
public static void main(String arr[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter Any Number : ");
int num=sc.nextInt();
SumOfDigit obj=new SumOfDigit();
int ans=obj.sod(num);
System.out.println("Sum of Digit of "+num+" is: "+ans);
}
}
Output
Enter Any Number :
1234
Sum of Digit of 1234 is: 10