🌟 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

✅ Conclusion

Finding the sum of digits is a classic beginner DSA problem.

👉 Always try writing both iterative and recursive versions for better practice!