DEV Community

MOHAMED ABDULLAH
MOHAMED ABDULLAH

Posted on

Sum of Digits in Java

What is "Sum of Digits"?
The Sum of Digits of a number means adding all individual digits of that number.

Example:

Input: 123

Calculation: 1 + 2 + 3 = 6

Key Concepts Used

Concept Description
Modulo % Gives the last digit of a number. 123 % 10 = 3
Division / Removes the last digit. 123 / 10 = 12
Loops Used to keep dividing and summing digits until the number
becomes 0
Type Works best with int, but can be extended to long,
BigInteger, etc.

Algorithm Steps
Initialize a variable to store the sum (e.g., sum = 0)

Use a while loop to repeat until the number becomes 0

In each iteration:

Get the last digit using number % 10

Add the digit to sum

Remove the last digit using number = number / 10

Print or return the result

example:

public class SumOfDigits {

public static void main(String[] args) {
    int number = 12345; // Example input
    int sum = 0;

    while (number != 0) {
        int digit = number % 10; // Get last digit
        sum += digit;            // Add to sum
        number = number / 10;    // Remove last digit
    }

    System.out.println("Sum of digits: " + sum);
}
Enter fullscreen mode Exit fullscreen mode

}

Top comments (0)