Anand Tyagi Anand Tyagi - 27 days ago 6
Java Question

How is recursion working in the following code?

void print (int n)
{
if (n>0)
{
printf("hello");
print(n-1);
}
printf("world");
}


In the code above, the hello is printed n times(which I get) and world is getting printed n+1 times(which I don't get at all). Shouldn't it print just for once, when the n=0? I mean its not returning anything to the calling function.
Thank You.

Answer

the hello is printed n times(which I get) and world is getting printed n+1 times(which I don't get at all).

This is how the instructions get executed in your case. "hello" gets executed for [n, 1] and "world" gets executed for [0, n].

n : printf("hello");
    n-1 : printf("hello");
          n-2 : printf("hello");
                ....
                    2 : printf("hello");
                        1 : printf("hello");
                            0 : printf("world");  << Difference is here
                        1 : printf("world");
                    2 : printf("world");    
                ....                            
          n-2 : printf("world");
    n-1 : printf("world");
n : printf("world");            
Comments