My first recursion program.
Qs: To calculate the sum of digits of a 5 digit number using recursion.
I can do it using functions. But the recursion way is not working. I admit, I did a lot of guess work and trial and error, but it did seem logical. Can you tell me where I'm wrong?
Code:
#include<stdio.h>
int main(void)
{
int d, sum, num;
printf("Enter number:");
scanf("%d", &num);
sum=rec(d); /* Here I get an error saying I haven't declared 'd', but I
have. */
printf("\nSum is %d", sum);
getch();
clrscr();
}
rec(d)
int d, num; /* Is this allowed? I did this because I didn't want the
rec to affect num */
{
int digit, s=0;
d=10000;
while(d>=1)
{
digit=(num/rec(d/10))%10;
s=s+digit;
}
return(s);
}