Reputation: 69
Here is my code :
#include<iostream>
int x;
void gad(int x)
{
if(x==0)
return;
else{
std::cout<<"geek"<<" ";
std::cout<<"for geeks ";
gad(x-1);
}
}
int main()
{
gad(3);
return 0;
}
The output is this
geek for geeks geek for geeks geek for geeks
Now if the change the position of 2nd std::cout
From
std::cout<<"geek"<<" ";
std::cout<<"for geeks ";
gad(x-1);
to
std::cout<<"geek"<<" ";
gad(x-1);
std::cout<<"for geeks ";
The output that came is this
geek geek geek for geeks for geeks for geeks
My question is why changing the position of std::cout
changes the output like that?
I thought if I put cout
after the function, due to recursion it won't give "for geeks" and come out of the recursive loop due to the if
statement.
Upvotes: 0
Views: 244
Reputation: 431
In the first case, you are printing both before making your recursive call. Whereas in the second scenario, you are first printing 'geeks', and making the recursive call, which again prints 'geeks' and so on, until it returns null, and then 'for geeks' is printed as it is sequentially the next statement after the recursive call.
Upvotes: 1
Reputation: 1330
You're printing the first sentence, then going into a recursive call to the same function which will, in return, print the first sentence and go to another recursive call...etc.
After the last function returns, it will continue with x=1
to print the second sentence...etc.
To visualize what happens, this will be the call stack:
x=3 ---> print first statement
x=2 ---> print first statement
x=1 ---> print first statement
x=0 ---> return
x=1 ---> continue to print second statement and terminate
x=2 ---> continue to print second statement and terminate
x=3 ---> continue to print second statement and terminate
Upvotes: 1