Java Program to Find Sum of Digits of a Number using Recursion

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.

  1. import java.util.Scanner;
  2. public class Digit_Sum 
  3. {
  4.     int sum = 0;
  5.     public static void main(String[] args) 
  6.     {
  7.         int n;
  8.         Scanner s = new Scanner(System.in);
  9.         System.out.print("Enter the number:");
  10.         n = s.nextInt();
  11.         Digit_Sum obj = new Digit_Sum();
  12.         int a = obj.add(n);
  13.         System.out.println("Sum:"+a);
  14.     }
  15.     int add(int n)
  16.     {
  17.         sum = n % 10;
  18.         if(n == 0)
  19.         {
  20.             return 0;
  21.         }
  22.         else
  23.         {
  24.              return sum + add(n / 10);
  25.         }
  26.  
  27.     }
  28. }

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]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.