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

CCC Online Test 2021 CCC Practice Test Hindi Python Programming Tutorials Best Computer Training Institute in Prayagraj (Allahabad) Best Java Training Institute in Prayagraj (Allahabad) Best Python Training Institute in Prayagraj (Allahabad) O Level Online Test in Hindi Bank SSC Railway TET UPTET Question Bank career counselling in allahabad Sarkari Naukari Notification Best Website and Software Company in Allahabad Sarkari Exam Quiz