Calculate the Sum of its Digits in Java


If a five-digit number is input through the keyboard, write a program to calculate the sum of its digits. ( Hint: Use the modulus operator '%')

The program first prompts the user to enter a five-digit number using the System.out.println statement and then reads the input using the Scanner class.

After that, the program uses the modulus operator % and the division operator / to extract each digit of the input number and add it to the sum variable. This is done by first calculating the remainder of the number when divided by 10, which gives the last digit of the number. The last digit is then added to the sum variable, and the number is divided by 10 to remove the last digit. This process is repeated four more times to extract all the digits of the number and add them to the sum variable.

Finally, the program outputs the sum of the digits using the System.out.println statement. Note that this program assumes that the user inputs a valid five-digit number. If the user inputs a number with fewer or more than five digits, the program may not work as intended.


Source Code

import java.util.Scanner;
class Sum_of_Digits
{
	public static void main(String args[])
	{
		Scanner input = new Scanner(System.in);
		System.out.println("Enter the Five Digits Numbers :");
		int num = input.nextInt();
		System.out.println("Original Digits :"+num);	
		int rem,sum=0;
		rem=num%10;
		num=num/10;
		sum=sum+rem;
 
		rem=num%10;
		num=num/10;
		sum=sum+rem;
 
		rem=num%10;
		num=num/10;
		sum=sum+rem;
 
		rem=num%10;
		num=num/10;
		sum=sum+rem;
 
		rem=num%10;
		sum=sum+rem;
		System.out.println("Sum of Digits :"+sum);
	}
}

Output

Enter the Five Digits Numbers :
57321
Original Digits :57321
Sum of Digits :18