-1

I'm trying to write as loop in java that takes a 3 digit number and adds the numbers together. For example 123 would equal 6. I know that n % 10 will get me the first digit 3 and then n/10 will get me 23 which can than then can be % 10 again to get me the second number. That doesn't work for the last number however. I can't figure out how to write the loop. Any help would be greatly appreciated.

1 Answers1

0
public static void main(String[] args) {
        int num = 321;
        int sum = 0;
        while (num > 0) {
            sum = sum + num % 10;
            num = num / 10;
        }
        System.out.println(sum);
    }

Duplicate: How to sum digits of an integer in java?

0liveradam8
  • 752
  • 4
  • 18