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; }
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; }
I don't see anything in the code that would cause you to go too deep on a recursion to get an access violation.
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); }
You aren't using recursion there dude, take a look here:Originally Posted by xephyr
http://cboard.cprogramming.com/showthread.php?t=55061
That's a good example of recursion explained step by step.
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?Originally Posted by Thantos
Code:p(n-2) ... p(n-1)
Wow I should be drunk when I posted before, sorry dude now I got itOriginally Posted by sean_mackrory
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.
>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.
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; }