0
0
JavaProgramBeginner · 2 min read

Java Program to Find Sum of Digits Using While Loop

You can find the sum of digits of a number in Java using a while loop by repeatedly extracting the last digit with num % 10, adding it to a sum, and then removing the last digit with num = num / 10 until the number becomes zero.
📋

Examples

Input123
OutputSum of digits: 6
Input0
OutputSum of digits: 0
Input99999
OutputSum of digits: 45
🧠

How to Think About It

To find the sum of digits, think of peeling off one digit at a time from the right side of the number. Use the remainder operator % to get the last digit, add it to a total sum, then remove that digit by dividing the number by 10. Repeat this until no digits remain.
📐

Algorithm

1
Get the input number.
2
Initialize sum to 0.
3
While the number is greater than 0:
4
Extract the last digit using remainder operator.
5
Add the digit to sum.
6
Remove the last digit by dividing the number by 10.
7
After the loop ends, return or print the sum.
💻

Code

java
import java.util.Scanner;

public class SumOfDigits {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int num = scanner.nextInt();
        int sum = 0;
        while (num > 0) {
            sum += num % 10;
            num /= 10;
        }
        System.out.println("Sum of digits: " + sum);
        scanner.close();
    }
}
Output
Enter a number: 123 Sum of digits: 6
🔍

Dry Run

Let's trace the input 123 through the code to see how the sum is calculated.

1

Initial values

num = 123, sum = 0

2

First iteration

sum = 0 + 123 % 10 = 0 + 3 = 3; num = 123 / 10 = 12

3

Second iteration

sum = 3 + 12 % 10 = 3 + 2 = 5; num = 12 / 10 = 1

4

Third iteration

sum = 5 + 1 % 10 = 5 + 1 = 6; num = 1 / 10 = 0

5

Loop ends

num is now 0, exit loop; sum = 6

numnum % 10sumnum after division
1233312
12251
1160
💡

Why This Works

Step 1: Extract last digit

Using num % 10 gets the last digit of the number because it gives the remainder when divided by 10.

Step 2: Add digit to sum

Add the extracted digit to the running total stored in sum.

Step 3: Remove last digit

Divide the number by 10 using integer division (num /= 10) to drop the last digit and prepare for the next iteration.

🔄

Alternative Approaches

Using recursion
java
public class SumOfDigits {
    public static int sumDigits(int num) {
        if (num == 0) return 0;
        return num % 10 + sumDigits(num / 10);
    }
    public static void main(String[] args) {
        int num = 123;
        System.out.println("Sum of digits: " + sumDigits(num));
    }
}
Recursion is elegant but uses more memory due to function calls.
Using for loop
java
public class SumOfDigits {
    public static void main(String[] args) {
        int num = 123;
        int sum = 0;
        for (; num > 0; num /= 10) {
            sum += num % 10;
        }
        System.out.println("Sum of digits: " + sum);
    }
}
For loop is a compact alternative but functionally similar to while loop.

Complexity: O(d) time, O(1) space

Time Complexity

The loop runs once for each digit in the number, so the time depends on the number of digits, denoted as d.

Space Complexity

Only a few variables are used, so space is constant, O(1).

Which Approach is Fastest?

The while loop and for loop approaches have similar speed and memory use; recursion uses more memory due to call stack overhead.

ApproachTimeSpaceBest For
While loopO(d)O(1)Simple and clear iteration
For loopO(d)O(1)Compact iteration syntax
RecursionO(d)O(d)Elegant code but uses more memory
💡
Always initialize your sum variable to zero before starting the loop.
⚠️
Forgetting to update the number inside the loop causes an infinite loop.