Write Java Program to find sum of digits of given number.

 Let's we have a number 65847 so sum of digits of given number is 30(6+5+8+4+7). We are going to use following logic to solve this problem.

1. we'll break the number using modulus operator by using while loop.
2.Then add all digits.

  1. public class SumOfDigits{
  2. public static void main(String [] args){
  3. int number = 65847;
  4. int sum = 0, digit;
  5. while(number!=0){
  6. remainder = number%10;
  7. sum = sum + digit;
  8. number = number/10;
  9. }
  10. System.out.println("Sum of digits of the given number is "+sum); // 30
  11. }
  12. }

0 comments:

Post a Comment