Write a Java method to compute the sum of the digits in an integer


This Java program accepts an integer input from the user and calculates the sum of its digits. Here's how it works:

  • The program starts by importing the java.util.Scanner class, which is used to read user input.
  • The main method is defined, which prompts the user to enter an integer and then reads the input using the Scanner class.
  • The sum_digits method is defined, which takes an integer parameter and calculates the sum of its digits using a while loop.
  • Inside the sum_digits method, we initialize a variable res to 0 to store the sum of digits.
  • We then use a while loop to extract the digits of the input number one by one. In each iteration of the loop, we use the modulo operator to get the last digit of the number and add it to res. We then divide the number by 10 to remove the last digit.
  • Once the loop is complete, we print the final sum of digits to the console using the System.out.println method.

Source Code

import java.util.Scanner;
public class Sum_Digits
{
	public static void main(String[] args)
	{
		Scanner input = new Scanner(System.in);
		System.out.print("Enter a Number : ");
		int digit = input.nextInt();
		sum_digits(digit);
	}
	public static void sum_digits(long n)
	{
		int res = 0;
		while(n > 0)
		{
			res += n % 10;
			n /= 10;
		}
		System.out.println("Sum : " + res);
	}	
}

Output

Enter a Number : 45
Sum : 9

Example Programs