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.
- public class SumOfDigits{
- public static void main(String [] args){
- int number = 65847;
- int sum = 0, digit;
- while(number!=0){
- remainder = number%10;
- sum = sum + digit;
- number = number/10;
- }
- System.out.println("Sum of digits of the given number is "+sum); // 30
- }
- }
0 comments:
Post a Comment