Data Structures and Algorithms (DSA)  

๐Ÿ“Find the Sum of Digits of a Number

๐ŸŒŸ 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:

  • Coding interviews ๐Ÿ“

  • Competitive programming ๐Ÿ†

  • Problem-solving practice for beginners ๐Ÿ‘ฉโ€๐Ÿ’ป

๐Ÿ”ข 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

  • Iterative method: O(d) where d = number of digits

  • Recursive method: O(d) recursion depth

  • Space Complexity:

    • Iterative = O(1)

    • Recursive = O(d) (stack memory)

๐ŸŽฏ 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!