the following code does not print anything . why?
Code:#include<iostream.h> #include<conio.h> void fn(int); int main() { fn(10); getch(); return(0); } void fn(int n) { static int i; for(i=0;i<=n;i++) fn(n-i); cout<<"anything\n" ; }
the following code does not print anything . why?
Code:#include<iostream.h> #include<conio.h> void fn(int); int main() { fn(10); getch(); return(0); } void fn(int n) { static int i; for(i=0;i<=n;i++) fn(n-i); cout<<"anything\n" ; }
well......first off ..... you keep calling fn() where n = 10....... n-i when i = 0 == n-0
that should eventually segfault if i'm thinking correctly.....
i seem to have GCC 3.3.4
But how do i start it?
I dont have a menu for it or anything.
A recursive function needs some kind of test which if true returns from the function instead of calling the function again. The first time through your for loop n=10 and i=0, so n-i=10. Then, you call your function again with 10 as the argument. So, your program takes a break from executing the first function call, and exectutes the second function call. For your second function call, n=10 and i=0, so n-i=10, and you call your function again with 10 as the argument. So, your program takes a break from executing the 2nd function call and executes your 3rd function call...and so on and so on in an infinite cycle of function calls.
Last edited by 7stud; 05-02-2005 at 08:34 AM.
but i have declared i as static shd'nt it retain its value, or how to correct it.
but everytime you call the function you destroy i's value by doing the i=0 in the for loop.