Java Programs

Sum the digits of a number using recursion

We will learn how to write a program in Java to sum the digits of a number using recursion.

Basically, the idea is to add up all the digits of an arbitrary number. Therefore, we will build our program logic accordingly.

If someone makes the input 1547, then our program should make the output after adding 1, 5, 4 and 7.

1+5+4+7 = 17.

So our program should make the output 17.

How will this Java program behave?

Our program should output after adding all the digits of a given number.

if someone entered 143, then our program should give 8 as output.

Program:

import java.util.*; 
 
class Main {
 
    static int sum=0,rem;
    static int sumOfDigits(int num) {
            sum = sum + (num%10);
            rem = num/10;
            if(rem > 0)
            {
                sumOfDigits(rem);
            }
            return sum;
    }

    public static void main(String ...args){
        int result;
        Scanner sc= new Scanner(System.in);
        System.out.print("Enter number- ");  
        int originalNum= sc.nextInt();  
        result = Main.sumOfDigits(originalNum);
        System.out.println("Sum = "+result);
    }

} 

Output:

Enter number- 15
Sum = 6

About the Author: Elavarasan PK

Technical Specialist, Intersoft Data Labs