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
advertisement
Here’s the list of Best Books in Java Programming, Data Structures and Algorithms.
If you find any mistake above, kindly email to [email protected]Related Posts:
- Practice Information Technology MCQs
- Practice Programming MCQs
- Practice BCA MCQs
- Check Java Books
- Apply for Java Internship