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
% 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
Code
#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; }
Dry Run
Let's trace the input 123 through the code
Initialize variables
num = 123, sum = 0, temp = 123
First loop iteration
sum = 0 + (123 % 10) = 3, temp = 123 / 10 = 12
Second loop iteration
sum = 3 + (12 % 10) = 3 + 2 = 5, temp = 12 / 10 = 1
Third loop iteration
sum = 5 + (1 % 10) = 5 + 1 = 6, temp = 1 / 10 = 0
Loop ends
temp is 0, exit loop
Print result
Sum of digits: 6
| temp | temp % 10 | sum |
|---|---|---|
| 123 | 3 | 3 |
| 12 | 2 | 5 |
| 1 | 1 | 6 |
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
#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; }
#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; }
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.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Iterative | O(d) | O(1) | General use, efficient |
| Recursive | O(d) | O(d) | Elegant code, small inputs |
| String conversion | O(d) | O(d) | Simple code, when input is string |
num % 10 to get the last digit and num /= 10 to remove it.