C# Program for Sum of Digits Using Recursion
int SumOfDigits(int n) { if (n == 0) return 0; return n % 10 + SumOfDigits(n / 10); } which adds the last digit to the sum of the remaining digits recursively.Examples
How to Think About It
% to get the last digit and integer division / to remove it. Add the last digit to the sum of digits of the remaining number by calling the same function again until the number becomes zero.Algorithm
Code
using System; class Program { static int SumOfDigits(int n) { if (n == 0) return 0; return n % 10 + SumOfDigits(n / 10); } static void Main() { int number = 123; Console.WriteLine("Sum of digits: " + SumOfDigits(number)); } }
Dry Run
Let's trace the number 123 through the recursive sum of digits function.
Initial call
SumOfDigits(123) calculates 123 % 10 = 3 and calls SumOfDigits(12)
Second call
SumOfDigits(12) calculates 12 % 10 = 2 and calls SumOfDigits(1)
Third call
SumOfDigits(1) calculates 1 % 10 = 1 and calls SumOfDigits(0)
Base case
SumOfDigits(0) returns 0
Returning sums
SumOfDigits(1) returns 1 + 0 = 1 SumOfDigits(12) returns 2 + 1 = 3 SumOfDigits(123) returns 3 + 3 = 6
| Call | Number | Last Digit | Recursive Call | Return Value |
|---|---|---|---|---|
| 1 | 123 | 3 | SumOfDigits(12) | 6 |
| 2 | 12 | 2 | SumOfDigits(1) | 3 |
| 3 | 1 | 1 | SumOfDigits(0) | 1 |
| 4 | 0 | 0 | Base case | 0 |
Why This Works
Step 1: Base Case
The recursion stops when the number becomes zero, returning 0 because there are no digits left to add.
Step 2: Extract Last Digit
Using n % 10 extracts the last digit of the number to add to the sum.
Step 3: Recursive Call
The function calls itself with n / 10 to process the remaining digits, building the sum step by step.
Alternative Approaches
using System; class Program { static int SumOfDigits(int n) { int sum = 0; while (n > 0) { sum += n % 10; n /= 10; } return sum; } static void Main() { int number = 123; Console.WriteLine("Sum of digits: " + SumOfDigits(number)); } }
using System; class Program { static int SumOfDigits(int n) { int sum = 0; foreach (char c in n.ToString()) { sum += c - '0'; } return sum; } static void Main() { int number = 123; Console.WriteLine("Sum of digits: " + SumOfDigits(number)); } }
Complexity: O(log n) time, O(log n) space
Time Complexity
The function calls itself once per digit, so the time grows with the number of digits, which is proportional to log base 10 of the number.
Space Complexity
Each recursive call adds a layer to the call stack, so space used is proportional to the number of digits (log n).
Which Approach is Fastest?
The iterative approach is faster and uses less memory because it avoids recursive call overhead, but recursion is elegant and easy to understand.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Recursion | O(log n) | O(log n) | Learning recursion, elegant code |
| Iteration (loop) | O(log n) | O(1) | Performance and memory efficiency |
| String conversion | O(log n) | O(log n) | Simple code, less efficient |