Program for Sum of Digits of a Number in Java, there are following step perform:-
- Create the object of scanner class and System.in to receive user input.
- The nextInt() method scans the next token of the input data as an “int”.
- Now initialize an integer number.
- Make one while loop to check number is not equal to zero.
- Find the remainder by using the modulo (%) operator. It gives the last digit of the number.
- In if condition to check reminder is equals to zero otherwise goes to else condition.
- Declare a variable sum to store the sum of numbers and initialize it to 0.
- Add the last digit to the variable sum.
- Divide the number by 10. It removes the last digit of the number.
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;
if (digit % 2 == 0) {
sum = sum + digit;
} else {
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