Welcome to the Java Programming Forums

The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

>> REGISTER NOW TO START POSTING

# Thread: Help in understanding this recursive method

1. ## Help in understanding this recursive method

We are learning recursion in my intro to Java class, and I am having a hard time understanding how the method in the example given works. Any explanation as to what is happening when the method is called would be appreciated.

Here is the code:

```public class Hanoi

private int n;
private int pegA;
private int pegB;

public Hanoi(int in_n, int in_pegA, int in_pegB)
{
n = in_n;
pegA = in_pegA;
pegB = in_pegB;
}

public void makemoves()
{
if (n==1)
System.out.format("%d ==> %d%n", pegA, pegB)
else
{
int otherPeg = 6 - pegA - pegB; // 1 + 2 + 3 =6
Hanoi firstmove = new Hanoi (n-1, pegA, otherPeg);
firstmove.makemoves();
System.out.format("%d ==> %d%n", pegA, pegB);
Hanoi secondmove = new Hanoi (n-1, otherPeg, pegB);
secondmove.makemoves();
}
}
}```

2. ## Re: Help in understanding this recursive method

Cross-posted here. Most appreciate it if when you cross-post a question, you provide links to the cross-post so we can avoid duplicating effort that's already been exerted. We're volunteers and value our free time as much as you do.

3. ## Re: Help in understanding this recursive method

@curmudgeon

Will do.

~~~~

So what order would the code execute in.

Obviously it would first run

```Hanoi firstmove = new Hanoi (n-1, pegA, otherPeg);
firstmove.makemoves();```

but then would it run Hanoi firstmove = new Hanoi (n-1, pegA, otherPeg) again, or would it run System.out.print?