0
0
CppProgramBeginner · 2 min read

C++ Program for Sum of Digits Using Recursion

You can find the sum of digits of a number in C++ using recursion by defining a function like int sumDigits(int n) { if (n == 0) return 0; return n % 10 + sumDigits(n / 10); } which adds the last digit to the sum of digits of the remaining number.
📋

Examples

Input123
Output6
Input0
Output0
Input9999
Output36
🧠

How to Think About It

To find the sum of digits using recursion, think of the number as a collection of digits. Take the last digit using n % 10, then call the same process on the rest of the number using n / 10. Keep doing this until the number becomes zero, then add all the digits together.
📐

Algorithm

1
Get the input number.
2
Check if the number is zero; if yes, return zero as the sum.
3
Find the last digit by taking the remainder when divided by 10.
4
Call the function recursively with the number divided by 10 (removing the last digit).
5
Add the last digit to the result of the recursive call and return it.
💻

Code

cpp
#include <iostream>
using namespace std;

int sumDigits(int n) {
    if (n == 0) return 0;
    return n % 10 + sumDigits(n / 10);
}

int main() {
    int number;
    cout << "Enter a number: ";
    cin >> number;
    cout << "Sum of digits: " << sumDigits(number) << endl;
    return 0;
}
Output
Enter a number: 123 Sum of digits: 6
🔍

Dry Run

Let's trace the number 123 through the code to see how the sum of digits is calculated.

1

Initial call

sumDigits(123) -> last digit 3 + sumDigits(12)

2

Second call

sumDigits(12) -> last digit 2 + sumDigits(1)

3

Third call

sumDigits(1) -> last digit 1 + sumDigits(0)

4

Base case

sumDigits(0) -> returns 0

5

Return values

sumDigits(1) = 1 + 0 = 1 sumDigits(12) = 2 + 1 = 3 sumDigits(123) = 3 + 3 = 6

Function CallLast DigitRemaining NumberPartial Sum
sumDigits(123)3123 + sumDigits(12)
sumDigits(12)212 + sumDigits(1)
sumDigits(1)101 + sumDigits(0)
sumDigits(0)--0
💡

Why This Works

Step 1: Base Case

The function stops calling itself when the number becomes zero, returning 0 to end recursion.

Step 2: Extract Last Digit

Using n % 10, the function gets the last digit of the number to add to the sum.

Step 3: Recursive Call

The function calls itself with the number divided by 10, removing the last digit, to process the remaining digits.

Step 4: Sum Accumulation

Each recursive call returns the sum of digits processed so far, adding the last digit until the full sum is returned.

🔄

Alternative Approaches

Iterative approach
cpp
#include <iostream>
using namespace std;

int sumDigitsIterative(int n) {
    int sum = 0;
    while (n > 0) {
        sum += n % 10;
        n /= 10;
    }
    return sum;
}

int main() {
    int number;
    cout << "Enter a number: ";
    cin >> number;
    cout << "Sum of digits: " << sumDigitsIterative(number) << endl;
    return 0;
}
This uses a loop instead of recursion, which can be easier to understand and avoids function call overhead.
Using string conversion
cpp
#include <iostream>
#include <string>
using namespace std;

int sumDigitsString(int n) {
    string s = to_string(n);
    int sum = 0;
    for (char c : s) {
        sum += c - '0';
    }
    return sum;
}

int main() {
    int number;
    cout << "Enter a number: ";
    cin >> number;
    cout << "Sum of digits: " << sumDigitsString(number) << endl;
    return 0;
}
This converts the number to a string and sums digits by character, which is simple but uses extra memory.

Complexity: O(log n) time, O(log n) space

Time Complexity

The function processes each digit once, and the number of digits is proportional to log base 10 of n, so time is O(log n).

Space Complexity

Each recursive call adds a layer to the call stack, so space used is proportional to the number of digits, O(log n).

Which Approach is Fastest?

The iterative approach uses O(1) space and is generally faster due to no function call overhead, but recursion is elegant and easy to understand.

ApproachTimeSpaceBest For
RecursiveO(log n)O(log n)Learning recursion, simple code
IterativeO(log n)O(1)Performance and memory efficiency
String ConversionO(log n)O(log n)Simple code, but uses extra memory
💡
Use recursion by breaking the problem into smaller parts: last digit plus sum of remaining digits.
⚠️
Forgetting the base case causes infinite recursion or stack overflow.