# Recursive factorial, what is wrong with my code?

• 07-24-2004
xephyr
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;  }```
• 07-24-2004
Thantos
I don't see anything in the code that would cause you to go too deep on a recursion to get an access violation.
• 07-24-2004
Robc
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); }```
;)
• 07-24-2004
Maragato
Quote:

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:
http://cboard.cprogramming.com/c-programming/55061-recursive-function-confusion.html
That's a good example of recursion explained step by step.
• 07-24-2004
Thantos
Um any function that calls itself IS recursion. In fact there are two recursion points in that function.
• 07-24-2004
Maragato
Quote:

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? :confused:
• 07-24-2004
sean
Code:

```p(n-2) ... p(n-1)```
• 07-24-2004
Maragato
Quote:

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:eek:
• 07-25-2004
viaxd
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.
• 07-25-2004
Robc
>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.
• 07-25-2004
xephyr
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) {         int answer;                 if (n==1) return 1;                 answer=factorial(n-1)*n;                 printf("%d\n", answer);                                 return answer; }```