write a program to sum of its Digits


This program reads an integer value from the user, calculates the sum of its digits, and then prints both the original number and the sum of its digits.

  • Scanner input = new Scanner(System.in);: This creates a new Scanner object called input that reads user input from the console.
  • System.out.print("Enter the Digits :"); : This displays the message "Enter the Digits :" on the console, prompting the user to enter a number.
  • int num = input.nextInt();: This reads an integer value entered by the user using the Scanner object and assigns it to the variable num.
  • int a = num; : This creates a new variable a and assigns the value of num to it. This is done so that we can print the original number later on.
  • int sum = 0; : This initializes a variable sum to 0, which will be used to store the sum of the digits.
  • int rem = 0; : This initializes a variable rem to 0, which will be used to store the remainder when we divide num by 10.
  • while(num>0) : This starts a while loop that will continue as long as num is greater than 0.
  • rem = num % 10; : This calculates the remainder when num is divided by 10 and assigns it to rem.
  • sum = sum + rem; : This adds rem to the variable sum.
  • num /= 10; : This divides num by 10 and assigns the result back to num. This removes the rightmost digit from num so that we can process the next digit in the next iteration of the while loop.
  • System.out.println("Given Digits :" + a); : This prints the original number entered by the user.
  • System.out.println("Sum of Digits :" + sum); : This prints the sum of the digits calculated in the program.

Source Code

import java.util.Scanner;
class Sum_Digits
{
	public static void main(String[] args)
	{
		Scanner input = new Scanner(System.in);        
		System.out.print("Enter the Digits :");
		int num = input.nextInt(); 
		int a = num;
		int sum = 0;
		int rem = 0;        
		while(num>0)
		{
			rem = num % 10;
			sum = sum + rem;
			num /= 10;
		}
		System.out.println("Given Digits :" + a);
		System.out.println("Sum of Digits :" + sum);
	}
}

Output

Enter the Digits :23634
Given Digits :23634
Sum of Digits :18

Example Programs