Issue
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.
Solution
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
Answered By - Mohammed Deifallah Answer Checked By - Clifford M. (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.