To find the sum of the digits of an integer, repeatedly take the last digit with % 10, add it to the running total and remove that digit with division by 10.
#include <stdio.h>
int sum_digits(int number) {
int sum = 0;
do {
int digit = number % 10;
if (digit < 0) {
digit = -digit;
}
sum += digit;
number /= 10;
} while (number != 0);
return sum;
}
int main(void) {
int number;
printf("Enter an integer: ");
if (scanf("%d", &number) != 1) {
printf("Invalid input.\n");
return 1;
}
printf("Sum of digits = %d\n", sum_digits(number));
return 0;
}
#include <stdio.h>
int sum_digits(int number) {
if (number == 0) {
return 0;
}
int digit = number % 10;
if (digit < 0) {
digit = -digit;
}
return digit + sum_digits(number / 10);
}
int main(void) {
int number = 12345;
printf("Sum of digits: %d\n", sum_digits(number));
return 0;
}
Output
Sum of digits: 15
#include <stdio.h>
int sum_digits(int number) {
int sum = 0;
do {
int digit = number % 10;
if (digit < 0) {
digit = -digit;
}
sum += digit;
number /= 10;
} while (number != 0);
return sum;
}
int main(void) {
int numbers[] = {123, 456, 789, 12};
size_t count = sizeof numbers / sizeof numbers[0];
for (size_t i = 0; i < count; i++) {
printf("Sum of digits of %d is %d\n",
numbers[i], sum_digits(numbers[i]));
}
return 0;
}
Output
Sum of digits of 123 is 6
Sum of digits of 456 is 15
Sum of digits of 789 is 24
Sum of digits of 12 is 3
The function above treats the minus sign as a sign, not as a digit. Therefore the digit sum of -12345 is still 15.
#include <stdio.h>
int sum_digits(int number) {
int sum = 0;
do {
int digit = number % 10;
if (digit < 0) {
digit = -digit;
}
sum += digit;
number /= 10;
} while (number != 0);
return sum;
}
int main(void) {
int number = -12345;
printf("Sum of digits of %d is %d\n",
number, sum_digits(number));
return 0;
}
Count the number of digits or continue to Armstrong numbers.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.