Thread: Recursive factorial, what is wrong with my code?

1. Recursive factorial, what is wrong with my code?

got access violation when running in VC++ 6

Code:
```#include<stdio.h>

void p(int n){

if(n > 0){
p(n - 2);
printf("%d ", n);
p(n - 1);
}
}
int main(void) {
p(4);

return 0;
}```

2. I don't see anything in the code that would cause you to go too deep on a recursion to get an access violation.

3. Just out of curiosity, how does that function calculate a factorial recursively? It really should look a bit more like this:
Code:
```int f(int n)
{
if (n < 2) {
return 1;
}

return n * f(n - 1);
}```

4. Originally Posted by xephyr
got access violation when running in VC++ 6

Code:
```#include<stdio.h>

void p(int n){

if(n > 0){
p(n - 2);
printf("%d ", n);
p(n - 1);
}
}
int main(void) {
p(4);

return 0;
}```
You aren't using recursion there dude, take a look here:
That's a good example of recursion explained step by step.

5. Um any function that calls itself IS recursion. In fact there are two recursion points in that function.

6. Originally Posted by Thantos
Um any function that calls itself IS recursion. In fact there are two recursion points in that function.
Can you please me point them cause I see just one?

7. Code:
```p(n-2)
...
p(n-1)```

8. Originally Posted by sean_mackrory
Code:
```p(n-2)
...
p(n-1)```
Wow I should be drunk when I posted before, sorry dude now I got it

9. it's strange that people first learn recursion by writing the factorial function, it's simple, but terribly inefficient and really a poor use of recursion and it's capabilities. Recursion is better used in text analysis, sorting and data structure manipulation.

10. >it's strange that people first learn recursion by writing the factorial function
Not strange at all really. As you said, it's simple and easy to trace. That makes it a good candidate for a first step into the concept of recursion. The same goes with the fibonacci recursive solution. Neither of them should be used in any real code, but they're a critical step for beginners.

11. Wrong code,sorry, Look at this

Code:
```#include <stdio.h>
int factorial(int n);
int main()
{

factorial(2);
for(;;);
return 0;
}
int factorial (int n)
{