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?
What you have there is an iterative solution, not a recursive one.
Recursion involves defining the problems in terms of a simpler version of the problem, all the time working towards a fixed end point.
The fixed end point in this case is any number less than 10, for which the value is that digit.
The transition to a simpler case (for numbers greater than 9) is simply to add the least significant digit to the result of the number divided by ten (integer division).
Since it's classwork, pseudo-code only I'm afraid.
If you follow that for the number
314
, you'll see what happens.n == 314
so it calculates314 % 10
to get4
and callsdigitSum(31)
.n == 31
so it calculates31 % 10
to get1
and callsdigitSum(3)
.n == 3
so it just returns3
1
and returned as4
.4
and returned as8
.Hence you end up with the digit sum of
8
for the number314
.To do recursion, create a function that recurses rather than using a for loop.