coderolls Staff
coderolls Staff Hi 👋🏼, At coderolls we write tutorials about Java programming language and related technologies.

Java Program To Calculate Sum Of All Digits Of A Number

To calculate the sum of all digits of a number

  1. First, we will get a reminder of the input number by the modulo operator (%) and add it to the sum variable.
  2. Second, we will divide the input number by 10 and assign it again to an input number variable.
  3. We will repeat the above process until the input number is not equal to zero.
  4. 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!

comments powered by Disqus