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

Here’s the list of Best Books in Java Programming, Data Structures and Algorithms.

advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification 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
I’m Manish - Founder and CTO at Sanfoundry. I’ve been working in tech for over 25 years, with deep focus on Linux kernel, SAN technologies, Advanced C, Full Stack and Scalable website designs.

You can connect with me on LinkedIn, watch my Youtube Masterclasses, or join my Telegram tech discussions.

If you’re in your 20s–40s and exploring new directions in your career, I also offer mentoring. Learn more here.