Learn how to find sum of digits of a number in Java. Here we will calculate the sum of digits of a given number using a while loop.
Code Explanation (Step-by-Step)
- Create an object of the Scanner class using System.in to receive user input.
- The sc.nextInt() method reads the entered value as an integer and store in num variables.
- Declare a variable sum and initialize it to 0 to store the sum of digits.
- Use a while loop to continue processing until the number becomes 0.
- Find the last digit using the modulo (%) operator.
- Add the extracted digit to the sum variable.
- Divide the number by 10 using the division (/) operator to remove the last digit.
- Repeat the process until all digits have been processed.
- Now print the sum of the digits.
import java.util.Scanner;
public class SumOfNumber {
public static void main(String[] args) {
System.out.println("Enter the digit number:");
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
int digit = 0;
int sum = 0;
while (num != 0) {
digit = num % 10;
sum = sum + digit;
num = num / 10;
}
sc.close();
System.out.println("Sum of digit is - " + sum);
}
}
output :-
Enter the digit number: 257
sum of digit is – 14
Remove Last Digit Using Division
The division (/) operator is used to remove the last digit from the number. When an integer is divided by 10, the fractional part is discarded, leaving only the remaining digits.
Here are some Java-related programs that will help you understand Java concepts better: