# Thread: basic recursion function question. typo in book?

1. ## basic recursion function question. typo in book?

Hi all I am very new to C and am using Sams Teach Yourself C in 21 days. I have come across a program in day 5 that has baffeled me. More specificaly, it is a recursive function that has confused me. The code is posted below. The book says that the function contiues to call itself until the if statement ( if a == 1) is true. To me, this seems likea typo in the book, and it wouldnt be the first one that I have come across. I say this because, if a does equal 1, then the function would return a value of 1, right? If this is indeed a typo, i would appreciate greatly if someone would explain how this function works for me. thanks a bunch))

Code:
```
unsigned int factorial(unsigned int a)
{
if (a == 1)
return 1;
else
{
a *= factorial(a-1);
return a;
}
}```

2. The last time the function is called, it does indeed return a 1, but since the last function call made was a *= factorial(a-1), you will just get the second-to-last returned value times 1, which of course is the second to last returned value.

Start with a 4 (or some other relatively low number) and walk through it, writing down the values as you go. Its a good way to figure out how recursive functions work.

3. It does call itself until a == 1. When a == 1 it returns 1, otherwise it calls itself, so the function calls itself until a == 1. I don't see the typo...

4. You might want to add a printf call in the function to help you see whats happening.

5. ok i have figured it out now. thanks for yall's help. the working it out on paper and adding the printf statements did it.

6. A more easier to see recursive factorial function that does the same thing would be something like:
Code:
```unsigned int factorial(unsigned int a)
{
if (a == 1)
return 1;
else {
return a * factorial(a-1);
}
}```
Here you can see the actual multiplication folding out, a * (a - 1) * (a - 2) * ... * 1. Just something extra

7. The last entry for recursion in K&R-II explains all you need to know about recursion