In this tutorial, we will be learning to write Java Program to print or calculate the sum of digits of a given number using a while loop. This program prints the sum of the digits of a number.
For Example:
Suppose the number is 12345,
Output should be (1+2+3+4+5) 15
Steps of program to calculate sum of input digit
- Here we are using “Scanner” to take input for numbers.
- We run a while loop till the number in check is not zero.
- Inside the loop, we are adding individual digits.
Suppose Given number = 12, sum=0 since 12>0 so it will go inside while loop to get the last digit of the number we are using the the modulo remainder property .i.e., 12%10 = 2 now, sum = 0+2 and the number is changed to 12/10 = 1. This will comtinue till the number < 0
Java Program to find the sum of digits of a given number
import java.util.*;
public class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int remainder,sum = 0;
System.out.println("Enter the Number to find Sum: ");
int number = sc.nextInt();
while(number>0) {
remainder = number%10;
sum=sum+remainder;
number = number/10;
}
System.out.println("Sum of the digits for the number is : " +sum+".");
sc.close();
}
}
Output 1
Enter the Number to find Sum:
3421
Sum of the digits for the number is : 10.
Output 2
Enter the Number to find Sum:
54671
Sum of the digits for the number is : 23.