user1405854
user1405854

Reputation:

Explanation of using recursion

class RecTest
{
    int values[];

    RecTest(int i)
    {
        values=new int[i];
    }

    void pray(int i)
    {
        if (i==0) return;
        else 
        {       
            System.out.println(+values[i-1]);
            pray(i-1);
        }
    }
}

class aka
{
    public static void main(String h[])
    {
        RecTest ob=new RecTest(10);
        int i;
        for(i=0;i<10;i++)
            ob.values[i]=i;
        ob.pray(10);
    }
}

This program works fine, it prints 9,8,7,6,5,4,3,2,1,0 in descending order. But when i interchange the System.out.println(+values[i-1]) and the pray(i-1) statements, it prints 0 to 9 in ascending order.

Can someone explain me why is that happening?

I just cant make sense out of it . Source-Java-2, A complete reference,5th Edition,page 171

Upvotes: 2

Views: 232

Answers (3)

Dawood ibn Kareem
Dawood ibn Kareem

Reputation: 79838

Written this way, your code says "print i-1, then do everything else". So it prints 9, then continues with the other numbers. In this context, "do everything else" means print 8, 7 and so on. But importantly, 9 gets printed first.

But if you reverse those two lines of code, it says "do everything else, then print i-1". So it deals with the other numbers, then prints 9. In this context, "deals with" means print ..., 7, 8. But importantly, 9 gets printed last.

Upvotes: 1

n00begon
n00begon

Reputation: 3492

It is changing whether you are printing on the way down the stack or coming back up. Either Print the current number then go deeper or go deeper then print the current number.

3 >
    2 >
        1 >
        print 1
    print 2
print 3

or

3
print 3 >
         2
         print 2 >
                  1
                  print 1

Upvotes: 7

cemulate
cemulate

Reputation: 2333

When you take this section

System.out.println(+values[i-1]);
pray(i-1);

And switch them, think about the progression of the code.

The execution steps into pray, but before it can print anything, it gets sent down into pray again, (this time with i = 8), and before it can print that, it gets sent down into pray again (with i = 7).

Finally, deep down in this chain, pray finally exits. When i = 0, pray returns, and the chain of execution slowing starts unwinding.

the print lowest in the chain gets called (when i = 0), and then THAT pray method exits, and the next print up in the chain gets called (i = 1)... etc...

It's a bit tough to visualize recursive code like this, but just try to imagine the exact flow of execution when your method is first called from main, and step through it step-by-step. Also, if you still can't see what's going on, stepping through with a debugger might be of help.

Upvotes: 2

Related Questions