Possible Duplicate:
What is recursion really and explain the output of this program?
What is really happening in this code?
I have a recursive function which I don’t understand. I don’t even know if the code is valid or not:
int count(int x) // suppose x is 3
{
if(x>0)
{
count(--x);
printf(x);
count(--x); // control reaches here or not?
}
}
This is just pseudocode. Take the initial variable as 3. Please explain with context the concept of stacks. This code is confusing me for days, and I can’t really find the answer for this code.
Ok, just because I needed to wake my brain up a bit 🙂
count(3)will enter the function and callcount(2)(2:nd level).count(2)will enter the function and callcount(1)(3:rd level).count(1)will enter the function and callcount(0)(4:th level).count(0)will enter the function, but sincex>0is false, it won’t do anything and just return to 4:th level wherexis still 0.4:th level will output
0, and callcount(-1)(5:th level)count(-1)will enter the function, but sincex>0is false, it won’t do anything and just return to 4:th level wherexis still -1.4:th level returns to 3:rd level where
xis still 1.3:rd level will output
1and callcount(0)(4:th level)count(0)will enter the function, but sincex>0is false, it won’t do anything and just return to 3:rd level wherexis still 0.3:rd level returns to 2:nd level where
xis still 2.2:nd level will output
2and callcount(1)(3:rd level)count(1)will enter the function and callcount(0)(4:th level).count(0)will enter the function, but sincex>0is false, it won’t do anything and just return to 3:rd level wherexis still 0.3:rd level will output
0and callcount(-1)(4:th level)count(-1)will enter the function, but sincex>0is false, it won’t do anything and just return to 3:rd level wherexis still -1.3:rd level returns to 2:nd level where
xis still 1.2:nd level returns to 1:st level and we’re done.
Output is
0 1 2 0.I suggest that if you really want to understand this, try it yourself with count(4).