Sum of Digits in Number

To find the sum of digits in number n in C programming, pop the last digit of number in a loop and accumulate it in a variable, until there are no digits left in the number.

C Program

In the following program, we read a number to n from user via console input, and find the sum of digits in this number.

main.c

#include <stdio.h>

int main() {
    int n;
    printf("Enter a number : ");
    scanf("%d", &n);
    
    int sum = 0;
    while (n > 0) {
        sum = sum + (n % 10);
        n = n / 10;
    }
    
    printf("Sum of digits : %d\n", sum);
}

Output

Enter a number : 523
Sum of digits : 10
Program ended with exit code: 0

Output

Enter a number : 12542
Sum of digits : 14
Program ended with exit code: 0

We have used C While Loop for iterating over the digits of given number.

ADVERTISEMENT

Conclusion

In this C Tutorial, we learned how to find the sum of digits in a number, with examples.