Sum of Digits of an Integer in C

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.

Sum the Digits with a Loop Top ↑

#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;
}

Recursive Sum of Digits Top ↑

#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

Sum Digits for an Array of Numbers Top ↑

#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

Negative Numbers Top ↑

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.





plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer