0
0
CsharpProgramBeginner · 2 min read

C# Program to Find Sum of Digits of a Number

To find the sum of digits in C#, use a loop to extract each digit with num % 10, add it to a sum, and reduce the number with num /= 10 until it becomes zero.
📋

Examples

Input123
Output6
Input0
Output0
Input9999
Output36
🧠

How to Think About It

To find the sum of digits, think of a number like a string of digits. You take the last digit by using 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

1
Get the input number.
2
Initialize sum to zero.
3
While the number is greater than zero:
4
Extract the last digit using modulus 10.
5
Add the digit to sum.
6
Remove the last digit by dividing the number by 10.
7
Return the sum.
💻

Code

csharp
using System;
class Program {
    static void Main() {
        int num = 123;
        int sum = 0;
        while (num > 0) {
            sum += num % 10;
            num /= 10;
        }
        Console.WriteLine(sum);
    }
}
Output
6
🔍

Dry Run

Let's trace the number 123 through the code to find the sum of its digits.

1

Initial values

num = 123, sum = 0

2

First iteration

sum = 0 + 123 % 10 = 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 0, stop loop, sum = 6

num before iterationdigit extractedsum after additionnum 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 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

Convert to string and sum digits
csharp
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);
    }
}
This method is easy to read but uses extra memory to convert the number to a string.
Recursive method
csharp
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));
    }
}
This uses recursion which is elegant but can cause stack overflow for very large numbers.

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.

ApproachTimeSpaceBest For
Loop with modulus and divisionO(d)O(1)Performance and memory efficiency
String conversion and iterationO(d)O(d)Readability and simplicity
Recursive methodO(d)O(d)Elegant code but risk of stack overflow
💡
Use integer division and modulus to handle digits without converting to strings for better performance.
⚠️
Forgetting to update the number by dividing by 10 inside the loop causes an infinite loop.