This is a Java Program to Find Sum of Digits of a Number using Recursion.
Enter any Decimal number as an input. Now we pass that number to a new functon where we use modulo operator to find sum of digits as ouput along with the help of recursion.
Here is the source code of the Java Program to Find Sum of Digits of a Number using Recursion. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.
import java.util.Scanner;
public class Digit_Sum
{
int sum = 0;
public static void main(String[] args)
{
int n;
Scanner s = new Scanner(System.in);
System.out.print("Enter the number:");
n = s.nextInt();
Digit_Sum obj = new Digit_Sum();
int a = obj.add(n);
System.out.println("Sum:"+a);
}
int add(int n)
{
sum = n % 10;
if(n == 0)
{
return 0;
}
else
{
return sum + add(n / 10);
}
}
}
Output:
$ javac Digit_Sum.java $ java Digit_Sum Enter the number:345 Sum:12
Sanfoundry Global Education & Learning Series - 1000 Java Programs.
advertisement
Here’s the list of Best Books in Java Programming, Data Structures and Algorithms.
Related Posts:
- Check Java Books
- Practice Programming MCQs
- Check Programming Books
- Apply for Computer Science Internship
- Practice BCA MCQs