Write a Java program to find the sum of digits of a number using recursion


This program calculates the sum of digits of a given number. Here is how it works:

  • It takes an input integer dig from the user using a Scanner object.
  • It initializes a static integer variable sum to 0.
  • It calls the sum_Digits method with dig as the argument.
  • The sum_Digits method checks if the input integer is greater than 0.
  • If yes, it calculates the last digit of the integer using the modulo operator and adds it to the sum variable.
  • It then recursively calls the sum_Digits method with the remaining digits obtained by dividing the input integer by 10.
  • This process continues until the input integer becomes 0.
  • Finally, the sum variable is returned, which holds the sum of all the digits in the input integer.
  • The result is then printed to the console using the System.out.printf method.

Source Code

import java.util.*;
public class SumOfDigits
{
	public static void main(String[] args)
	{
		Scanner input = new Scanner(System.in);
		int dig, res ;
		System.out.print("Enter the Digits : ");
		dig = input.nextInt();
		res = sum_Digits(dig);
		System.out.printf("Sum of Digits : " + res);
	}
	static int sum = 0;
	public static int sum_Digits(int dig)
	{
		if (dig > 0)
		{
			sum += (dig % 10);
			sum_Digits(dig / 10);
		}
		return sum;
	}
}

Output

Enter the Digits : 12398
Sum of Digits : 23