logo
Course thumb

The C programming language made simple

How to add all digits of a number in C

#include <stdio.h> #include <stdlib.h> #include <string.h> int sumOfDigits(int n) { int sum = 0; while (n > 0) { int d = n % 10; n = n / 10; sum += d; } } int main(int argc, char* argv[]) { int x = 38511; printf("Sum of the digits of %d is %d\n", x, sumOfDigits(x)); return 0; }