๐ Introduction
Finding the sum of digits of a number is one of the simplest yet most important problems in Data Structures and Algorithms (DSA). It helps beginners practice the concepts of loops, conditionals, and recursion.
๐ Example
If the number is 1234
,
Sum of digits = 1 + 2 + 3 + 4 = 10
.
This problem is very common in:
๐ข Problem Statement
Given a number, find the sum of its digits.
Example 1
Input: 987
Output: 9 + 8 + 7 = 24
Example 2
Input: 12345
Output: 15
๐ ๏ธ Different Approaches
There are multiple ways to solve this problem:
1๏ธโฃ Using While Loop (Iterative Method)
We extract each digit using the modulo operator %
and divide the number by 10
in every step until it becomes 0
.
#include <stdio.h>
int main() {
int num, sum = 0, digit;
printf("Enter a number: ");
scanf("%d", &num);
while (num > 0) {
digit = num % 10; // extract last digit
sum += digit; // add it to sum
num /= 10; // remove last digit
}
printf("Sum of digits = %d\n", sum);
return 0;
}
๐ Example
Input: 1234
โ Output: 10
2๏ธโฃ Using Recursion
We can solve this problem recursively by continuously breaking the number into digits.
#include <stdio.h>
int sumOfDigits(int num) {
if (num == 0)
return 0;
return (num % 10) + sumOfDigits(num / 10);
}
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
printf("Sum of digits = %d\n", sumOfDigits(num));
return 0;
}
๐ Example
Input: 567
โ Output: 18
3๏ธโฃ Using Mathematical Formula (Only for Specific Cases)
If the number is a repetition of digits like 999...9
, then sum can be quickly found:
For example, if num = 999
,
Sum = 9 * number_of_digits = 9 * 3 = 27
.
But this method is limited and not general.
๐ Time Complexity Analysis
๐ฏ Applications in Real Life
Digital root calculation (used in checksum algorithms like ISBN).
Numerology calculations ๐ข.
Error detection in financial transactions.
Cryptography & Hashing, where digit sums are used in transformations.
โ
Conclusion
Finding the sum of digits is a classic beginner DSA problem.
You can solve it using loops or recursion.
It improves your understanding of modulus, division, and recursion concepts.
๐ Always try writing both iterative and recursive versions for better practice!