Index « Previous Next »

Question

Write a recursive function that accepts a number as its argument and returns the sum of digits. Call the function in main().

Source Code

#include <stdio.h>

int sumDigits(int);

int main()
{
    int number, sum;

    printf("Enter a number: ");
    scanf("%d", &number);
    sum = sumDigits(number);
    printf("Sum of digits of %d is %d", number, sum);
    return 0;
}

int sumDigits(int i)
{
    if (i < 10)
    {
        return i;
    }
    else
    {
        return i % 10 + sumDigits(i / 10);
    }
}

Output

Enter a number: 149
Sum of digits of 149 is 14