Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can someone please explain me how this type of recursion works?

Tags:

c

recursion

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.

like image 543
Tania Avatar asked Aug 06 '14 15:08

Tania


People also ask

What is recursion explain how it 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.

How a recursion works describe with example?

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.

What is a good example of recursion?

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 .


2 Answers

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
like image 162
haccks Avatar answered Nov 15 '22 11:11

haccks


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.

like image 36
Stuart Golodetz Avatar answered Nov 15 '22 10:11

Stuart Golodetz