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.
Asked
Active
Viewed 555 times
-1
-
`%10` gets you the 10's place, `%100` gets you the 100's place, etc... see the pattern? – takendarkk Aug 17 '17 at 19:03
1 Answers
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