Hi. Can someone help me analyze this code. I think it runs into an infinite loop at n=3.
Thanks.Code:Fr(n): if n=1 print n; else for i=1 to n-1 do Fr(i)
Hi. Can someone help me analyze this code. I think it runs into an infinite loop at n=3.
Thanks.Code:Fr(n): if n=1 print n; else for i=1 to n-1 do Fr(i)
if ypou are going to play n-1 as an ending parameter you must decrease n somewhere,
Look at this. It seems to run as I was told it should. For example when n=6 the function outputs "1" 16 times. Why?!
I can't understand it.Code:#include<iostream> #include<cstdlib> using namespace std; void Fr(int); int main() { int n; n=0; cout<<"Please enter a value for n: "<<endl; cin>>n; Fr(n); system("pause"); return 0; } void Fr(int m) { int i; if(m==1) { cout<<m<<endl; } else { for(i=1; i<=m-1; i++) Fr(i); } }
>I can't understand it.
That's no surprise. You're mixing recursion with iteration and loop indices with the original argument that was not a loop index to begin with.
Start at the top with, say, m = 3. Going from the outside in, we realize that the outer most call will loop twice because i starts at 1 and goes to m - 1. Then we break away from m and call Fr with the loop index 1 that starts from 1 every time.
The first iteration of the loop is 1, so m is printed in the first recursive call. In the second recursive call, m is 2 so m is not printed and the first recursive loop begins. Because m is 2, the loop only executes once with the argument of 1, thus printing the value of m.
After this all recursive paths return and the output is:
Use the same logical progression for larger values of m and you'll have a good understanding of how this function works.Code:1 1
My best code is written with the delete key.