0
0
CppProgramBeginner · 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
OutputSum of digits: 6
Input0
OutputSum of digits: 0
Input99999
OutputSum of digits: 45
🧠

How to Think About It

To find the sum of digits, think of a number as a collection of single digits. You can get the last digit by using the remainder operator % with 10. Add this digit to a total sum. Then remove the last digit by dividing the number by 10. Repeat this until the number is zero.
📐

Algorithm

1
Get input number from the user
2
Initialize sum to zero
3
While number is greater than zero:
4
Extract last digit using remainder operator
5
Add extracted digit to sum
6
Remove last digit by dividing number by 10
7
Print the sum
💻

Code

cpp
#include <iostream>
using namespace std;

int main() {
    int num, sum = 0;
    cout << "Enter a number: ";
    cin >> num;
    int temp = num;
    while (temp > 0) {
        sum += temp % 10;
        temp /= 10;
    }
    cout << "Sum of digits: " << sum << endl;
    return 0;
}
Output
Enter a number: 123 Sum of digits: 6
🔍

Dry Run

Let's trace the input 123 through the code

1

Initialize variables

num = 123, sum = 0, temp = 123

2

First loop iteration

sum = 0 + (123 % 10) = 3, temp = 123 / 10 = 12

3

Second loop iteration

sum = 3 + (12 % 10) = 3 + 2 = 5, temp = 12 / 10 = 1

4

Third loop iteration

sum = 5 + (1 % 10) = 5 + 1 = 6, temp = 1 / 10 = 0

5

Loop ends

temp is 0, exit loop

6

Print result

Sum of digits: 6

temptemp % 10sum
12333
1225
116
💡

Why This Works

Step 1: Extract last digit

Using temp % 10 gives the last digit of the number, which we add to the sum.

Step 2: Remove last digit

Dividing temp by 10 with /= removes the last digit, moving to the next digit.

Step 3: Repeat until done

We repeat this process until temp becomes zero, meaning all digits are processed.

🔄

Alternative Approaches

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

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

int main() {
    int num;
    cout << "Enter a number: ";
    cin >> num;
    cout << "Sum of digits: " << sumDigits(num) << endl;
    return 0;
}
Uses recursion to sum digits; elegant but uses call stack which may be less efficient for very large numbers.
String conversion approach
cpp
#include <iostream>
#include <string>
using namespace std;

int main() {
    string numStr;
    cout << "Enter a number: ";
    cin >> numStr;
    int sum = 0;
    for (char c : numStr) {
        sum += c - '0';
    }
    cout << "Sum of digits: " << sum << endl;
    return 0;
}
Converts number to string and sums digits by character; simple but uses extra memory for string.

Complexity: O(d) time, O(1) space

Time Complexity

The loop runs once for each digit in the number, so time is proportional to the number of digits, 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 iterative approach is fastest and uses least memory. Recursive uses call stack, string method uses extra memory.

ApproachTimeSpaceBest For
IterativeO(d)O(1)General use, efficient
RecursiveO(d)O(d)Elegant code, small inputs
String conversionO(d)O(d)Simple code, when input is string
💡
Use num % 10 to get the last digit and num /= 10 to remove it.
⚠️
Forgetting to update the number inside the loop causes an infinite loop.