Search code examples
crecursionsumdigits

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


For instance , the number is 123, the answer is 6. Only recursion!


Solution

  • 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.