I have a school project to write a recursive function that takes one parameter of type int and it should output integers 1,2,3...n. n being the parameter of the recursive function. I have written the program below and it seems to be working perfectly fine.
#include <iostream>
usingnamespace std;
void myRecursive(int n);
int main()
{
int m;
cout << "Enter any integer ";
cin >> m;
cout <<endl;
myRecursive(m);
cout << endl;
system("PAUSE");
return 0;
}
void myRecursive(int n)
{
if(n == 1)
cout << n <<" ";
else
{
myRecursive(n - 1);
cout << n <<" ";
}
}
My problem is that i don't understand how the program gets to execute the statement cout << n <<" "; in the else part of the if-else statement because the function myRecursive(n -1) gets called before the cout << n <<" "; statement. As far as I am concerned the statement cout << n <<" "; should not be executed because the else part of the if-else statement does not finish executing as it gets interrupted by a call to myRecursive(n-1).
It's because the code is still sequential. Once myRecursive has run for that iteration, the next job is to run the line below.
The function keeps nesting inside itself. So consider that once you've got to the last branch of recursion, the program is going to come back out of that function for each call and run the next line, meaning it's got a bunch of cout << n << " "; statements to run.
It's a mind-bender at first, but give it some thought and it'll drop. :-)
It is a bit confusing, but i think I understand it now that you've explained it. So basically it's like the function keeps a copy of itself until it executes the base case (or stopping case) and then it goes backwards finishing the execution of each copy of myRecursive(n-1). I hope this makes sense.
myRecursive(3)
{
if(n == 1)
cout << n << " ";
else
{
myRecursive(n-1) // So, 2 runs here
{
if(n == 1)
cout << n << " ";
else
{
myRecursive(n-1) // 1 runs here
{
if(n==1)
cout << n << " ";
else
{
myRecursive(n-1);
cout << n << " ";
}
} // Leave 1
cout << n << " ";
}
} // Leave 2
cout << n << " ";
}
}
It's probably a little messy, but if you follow the branches through that's how it logically works. Notice that any time it leaves the scope of a call to the myRecursive function it has a cout statement right after.