+ 3
question print order problem
Int this problem the answer is 012345; Why it gives in that order, when the first to print is 5; so the answer should be 543210...??? void recurse(int u){ if(u >0){ recurse(u-1); } cout<< u; } int main() { int i=5; recurse(i); }
6 odpowiedzi
+ 1
Awesome Question
+ 6
Awesome answer by Rishi Anand,
I ll just add.
when a function calls another function then the control of execution goes to next function. But we also have to remember that previous function also needs to complete its execution,
This is why, whenever we have a function that calls another function we put the function in call stack to remember to complete it too.
REAL LIFE REFERENCE
suppose I am cooking( I pushed cooking to call stack in my brain and it's the top item so it's executing right now),
now I got a message then I pushed "reading" to call stack in my brain(now it's the top item and executing), and as soon as I finish reading I ll get back to cooking.
that's how call stack in function works, ( LIFO mode)
+ 3
here you should know the concept of stack i.e. Last In, First out
In recursion, the methods gets insered into the call stack. And the property of the stack is that the last one which is inserted will execute first.
find below the sequence of insertion
recurse(0)//6th method to be inserted in stack
recurse(1)//5th method to be inserted in stack
recurse(2)//4th method to be inserted in stack
recurse(3)//3rd method to be inserted in stack
recurse(4)//2nd method to be inserted in stack
recurse(5)//1st method to be inserted in stack
find below the sequence of execution
recurse(0)//executes 1st
recurse(1)//executes 2nd
recurse(2)//executes 3rd
recurse(3)//executes 4th
recurse(4)//executes 5th
recurse(5)//executes last
+ 2
This is the by default property of recursion in every programming language
If you want to check just run the recursion infinitely by removing the if statement and you will get stack overflow error
//this will give u stack overflow error
void recurse(int u)
{
recurse(u-1);
cout<<u;
}
+ 2
Gustavo A C
If you put the
cout <<u;
Before the if block you ll get the desired outcome,
543210
+ 1
They should be use stack instead..