Program for Sum of Digits of a Number in Java

Here we will create Java Program for Sum of Digits of a Number in Java.

Using While loop :-

  • Create the scanner class object to pass user input.
  • User input is store in n.
  • Declare a variable sum to store value and initialize to 0.
  • Initialize reminder to 0 and it is use modulo(%) operator to give last digit number of user input value.
  • Add the last digit value with sum.
  • Divide the number(n) by 10. it remove the last number of digit.
  • Now print the sum of digit number.
				
					import java.util.Scanner;

public class SumOfDigit {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int sum = 0, reminder = 0;
		System.out.println("enter the number:");
		int n = sc.nextInt();
		while (n != 0) {
			reminder = n % 10;
			sum = sum + reminder;
			n = n / 10;
		}
		System.out.println("the sum of digits is:- " + sum);
	}
}
				
			

Output :-
enter the number:
12
the sum of digits is:- 3