I came across this problem in recursion. I can't figure out how it works. I understand the basics of recursion but this totally confuses me. Please help.
main() {
foo(3);
}
void foo(int x) {
if (x >= 1) {
foo(--x);
printf("%d", x);
foo(--x);
}
}
I thought this program wouldn't print anything but it prints 0120 .
Doesn't the first call to foo(--3) i.e foo(2) jump to the beginning of the function and recur till 3 decrements to 0?
Please explain how this works.
Recursion means “solving the problem via the solution of the smaller version of the same problem” or “defining a problem in terms of itself”. It is a widely used idea in programming to solve complex problems by breaking them down into simpler ones.
Recursion is the process of defining a problem (or the solution to a problem) in terms of (a simpler version of) itself. For example, we can define the operation "find your way home" as: If you are at home, stop moving. Take one step toward home.
A classic example of recursion For example, factorial(5) is the same as 5*4*3*2*1 , and factorial(3) is 3*2*1 .
The first call to foo()
can be explained using a recursion tree:
prints (in reverse order)
2 <---------- foo(3)
/ \
1 <----- foo(2) foo(1) -----> 0
/ \ / \
0 <-- foo(1) foo(0) foo(0) foo(-1)
/ \
foo(0) foo(-1)
First, the left sub-tree will be evaluated and will print 012
and then the right sub-tree will be evaluated and will print 0
. Finally you get the output:
0120
So foo(3) is:
foo(2)
print 2
foo(1)
And foo(2) is:
foo(1)
print 1
foo(0)
And foo(1) is:
foo(0)
print 0
foo(-1)
Now foo(0) and foo(-1) are no-ops, so foo(1) is:
print 0
Whence foo(2) is:
print 0
print 1
And foo(3) is:
print 0
print 1
print 2
print 0
This gives you the observed output.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With