0
0
CProgramBeginner · 2 min read

C Program to Find Sum of Digits Using While Loop

You can find the sum of digits in C using a while loop by repeatedly extracting the last digit with digit = num % 10, adding it to a sum, and then removing the last digit with num = num / 10 until num becomes zero.
📋

Examples

Input123
OutputSum of digits = 6
Input0
OutputSum of digits = 0
Input9999
OutputSum of digits = 36
🧠

How to Think About It

To find the sum of digits, think of a number as a collection of single digits. Extract the last digit by using the remainder operator %, add it to a total sum, then remove that digit by dividing the number by 10. Repeat this until no digits remain.
📐

Algorithm

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

Code

c
#include <stdio.h>

int main() {
    int num, sum = 0, digit;
    printf("Enter a number: ");
    scanf("%d", &num);

    if (num == 0) {
        printf("Sum of digits = 0\n");
        return 0;
    }

    while (num > 0) {
        digit = num % 10;
        sum += digit;
        num /= 10;
    }

    printf("Sum of digits = %d\n", sum);
    return 0;
}
Output
Enter a number: 123 Sum of digits = 6
🔍

Dry Run

Let's trace the input 123 through the code

1

Initial values

num = 123, sum = 0

2

First iteration

digit = 123 % 10 = 3; sum = 0 + 3 = 3; num = 123 / 10 = 12

3

Second iteration

digit = 12 % 10 = 2; sum = 3 + 2 = 5; num = 12 / 10 = 1

4

Third iteration

digit = 1 % 10 = 1; sum = 5 + 1 = 6; num = 1 / 10 = 0

5

Loop ends

num is now 0, exit loop and print sum = 6

num before iterationdigit extractedsum after additionnum after division
1233312
12251
1160
💡

Why This Works

Step 1: Extract last digit

Using num % 10 gets the last digit of the number because it gives the remainder after division by 10.

Step 2: Add digit to sum

Add the extracted digit to the running total stored in sum.

Step 3: Remove last digit

Divide the number by 10 using integer division num /= 10 to discard the last digit and move to the next.

Step 4: Repeat until done

Continue the loop until num becomes zero, meaning all digits have been processed.

🔄

Alternative Approaches

Using for loop with string input
c
#include <stdio.h>
#include <string.h>

int main() {
    char num[20];
    int sum = 0;
    printf("Enter a number: ");
    scanf("%s", num);

    for (int i = 0; i < strlen(num); i++) {
        sum += num[i] - '0';
    }

    printf("Sum of digits = %d\n", sum);
    return 0;
}
This method treats the number as a string and sums digits by converting characters to integers; useful for very large numbers but uses more memory.
Using recursion
c
#include <stdio.h>

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

int main() {
    int num;
    printf("Enter a number: ");
    scanf("%d", &num);
    printf("Sum of digits = %d\n", sumDigits(num));
    return 0;
}
Recursion is elegant but can use more stack space; good for learning but less efficient for very large inputs.

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

Time Complexity

The loop runs once for each digit in the number, so time complexity is proportional to the number of digits, O(d).

Space Complexity

Only a few integer variables are used, so space complexity is constant, O(1).

Which Approach is Fastest?

The while loop method is fastest and uses least memory compared to string or recursive methods.

ApproachTimeSpaceBest For
While loop with integerO(d)O(1)Simple and efficient for normal integers
For loop with string inputO(d)O(d)Very large numbers or when input is string
RecursionO(d)O(d)Learning recursion, less efficient for large inputs
💡
Always initialize your sum variable to zero before starting the loop to avoid garbage values.
⚠️
Forgetting to update the number inside the loop causes an infinite loop.