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;

}

Printable View

- 07-24-2004xephyrRecursive 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-2004Thantos
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-2004Robc
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-2004MaragatoQuote:

Originally Posted by**xephyr**

http://cboard.cprogramming.com/c-programming/55061-recursive-function-confusion.html

That's a good example of recursion explained step by step. - 07-24-2004Thantos
Um any function that calls itself

**IS**recursion. In fact there are two recursion points in that function. - 07-24-2004MaragatoQuote:

Originally Posted by**Thantos**

- 07-24-2004seanCode:
`p(n-2)`

...

p(n-1)

- 07-24-2004MaragatoQuote:

Originally Posted by**sean_mackrory**

- 07-25-2004viaxd
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-2004Robc
>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-2004xephyrWrong code,sorry, Look at thisCode:
`#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;

}