Sum of Digits using recursion in C

JustAStudent picture JustAStudent · Aug 30, 2013 · Viewed 9.6k times · Source

For our activity today, we were tasked to make using recursion with the sum of digits. I already made this program:

int main()

{
int num = 0, sum;

printf("Enter an integer: ");
scanf("%d",&num);

//counter=1;

for ( sum=0; num>0;)

{
    sum = sum + num % 10;
    num = num /10;
  }
printf("Sum = %d", sum);

getch();
return 0;

}

Our teacher added "Input and output must be done in the main() function." Am doing the right thing? Or am I missing something in my code?

Answer

chux - Reinstate Monica picture chux - Reinstate Monica · Aug 30, 2013

To do recursion, create a function that recurses rather than using a for loop.

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


scanf("%d", &i);
printf("%d\n", SumDigits(i));