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

Online Exam Quiz for One day Exam Online Typing Test CCC Online Test 2026 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 Best Website and Software Company in Allahabad