Java Program To Calculate Sum Of All Digits Of A Number
To calculate the sum of all digits of a number
- First, we will get a reminder of the input number by the modulo operator (%) and add it to the
sum
variable. - Second, we will divide the input number by 10 and assign it again to an input number variable.
- We will repeat the above process until the input number is not equal to zero.
- At the end we will have the sum of all the digits of a number in the
sum
variable.
Let’s a Java program to calculate the sum of all digits of a number.
Java Program
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* A Java program to calculate the sum of all digits of a given number
* By coderolls.com
*/
public class SumOfAllDigits {
public static void main(String[] args) {
int number = 1256;
int sum = sumOfAllDigits(number);
System.out.println("The sum of all digits of " + number + " is: "+ sum);
}
private static int sumOfAllDigits(int number) {
int sum =0;
while(number!=0){
int reminder = number%10;
sum = sum + reminder;
number = number/10;
}
return sum;
}
}
Output
1
The sum of all digits of 1256 is: 14
Join Newsletter
Get the latest tutorials right in your inbox. We never spam!