[Solved] How to sum the digits of a number using Recursion [C]? [closed]


While @SamGrondahl is on the right track, unfortunately, if you enter a negative number it gives unexpected results. This should work properly with negative numbers:

int sumdigits(int number) {
    int sign = number < 0 ? -1 : 1;
    number = sign * number; // abs the number

    if (number < 10) 
        return sign * number;
    else 
        return sign * (number % 10 + sumdigits(number / 10));
}

This will return the sum of the digits, and if the number is negative, negate that.

solved How to sum the digits of a number using Recursion [C]? [closed]