C# Program to Find Sum of Digits of a Number
num % 10, add it to a sum, and reduce the number with num /= 10 until it becomes zero.Examples
How to Think About It
modulus 10, add it to a total sum, then remove that digit by dividing the number by 10. Repeat this until no digits remain.Algorithm
Code
using System; class Program { static void Main() { int num = 123; int sum = 0; while (num > 0) { sum += num % 10; num /= 10; } Console.WriteLine(sum); } }
Dry Run
Let's trace the number 123 through the code to find the sum of its digits.
Initial values
num = 123, sum = 0
First iteration
sum = 0 + 123 % 10 = 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 0, stop loop, sum = 6
| num before iteration | digit extracted | sum after addition | 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 after division 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 System; class Program { static void Main() { int num = 123; int sum = 0; foreach (char c in num.ToString()) { sum += c - '0'; } Console.WriteLine(sum); } }
using System; class Program { static int SumDigits(int n) { if (n == 0) return 0; return n % 10 + SumDigits(n / 10); } static void Main() { int num = 123; Console.WriteLine(SumDigits(num)); } }
Complexity: O(d) time, O(1) space
Time Complexity
The loop runs once for each digit in the number, so time depends on the number of digits, which is O(d).
Space Complexity
Only a few variables are used regardless of input size, so space complexity is O(1).
Which Approach is Fastest?
The loop with modulus and division is fastest and uses least memory compared to string conversion or recursion.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Loop with modulus and division | O(d) | O(1) | Performance and memory efficiency |
| String conversion and iteration | O(d) | O(d) | Readability and simplicity |
| Recursive method | O(d) | O(d) | Elegant code but risk of stack overflow |