Java Program to Find Sum of Digits Using While Loop
num % 10, adding it to a sum, and then removing the last digit with num = num / 10 until the number becomes zero.Examples
How to Think About It
% 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
Code
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(); } }
Dry Run
Let's trace the input 123 through the code to see how the sum is calculated.
Initial values
num = 123, sum = 0
First iteration
sum = 0 + 123 % 10 = 0 + 3 = 3; num = 123 / 10 = 12
Second iteration
sum = 3 + 12 % 10 = 3 + 2 = 5; num = 12 / 10 = 1
Third iteration
sum = 5 + 1 % 10 = 5 + 1 = 6; num = 1 / 10 = 0
Loop ends
num is now 0, exit loop; sum = 6
| num | num % 10 | sum | num after division |
|---|---|---|---|
| 123 | 3 | 3 | 12 |
| 12 | 2 | 5 | 1 |
| 1 | 1 | 6 | 0 |
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
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)); } }
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); } }
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.
| Approach | Time | Space | Best For |
|---|---|---|---|
| While loop | O(d) | O(1) | Simple and clear iteration |
| For loop | O(d) | O(1) | Compact iteration syntax |
| Recursion | O(d) | O(d) | Elegant code but uses more memory |