### Sum of digits of a number

Below program shows how to find out sum of each digit in the given number logic. For example, if the number is 259, then the sum should be 2+5+9 = 16.

**PROGRAM**import java.util.Scanner; class SumOfDigits { public static void main(String[] args) { int num, sum=0; Scanner input = new Scanner(System.in); System.out.print("Enter the number :: "); num = input.nextInt(); while(num > 0) { sum = sum + (num % 10); num = num / 10; } System.out.println("Sum of digits is :: " + sum); } }

**OUTPUT 1**C:\>javac SumOfDigits.java C:\>java SumOfDigits Enter the number :: 123 Sum of digits is :: 6

**OUTPUT 2**C:\>javac SumOfDigits.java C:\>java SumOfDigits Enter the number :: 456 Sum of digits is :: 15

## Comments

## Post a Comment