bugl
bugl
HomeLearnPatternsPathsSearchPremium
HomeLearnPatternsPaths

Loading lesson path

Learn/Java/Java How To's
Java•Java How To's

Java How To - Sum of Digits

Sum of Digits of a Number

Add up all digits (e.g., 352: 3 + 5 + 2 = 10):

Example

int n = 352;
int sum = 0;
while (n > 0) {
  sum += n % 10;
  n /= 10;
}
System.out.println("Sum of digits: " + sum);

Explanation: We use n % 10 to extract the last digit, add it to the sum, and then remove the digit with n /= 10 .

Previous

Java How To - Convert Celsius to Fahrenheit

Next

Java How To Check Armstrong Number