Venzentx
Venzentx

Reputation: 487

Tower of Hanoi's return in java

public static void solveTowers(int disks, int sourcePeg, int destinationPeg, int tempPeg)
{
    //always set the base case in any type of recursion programs
    if(disks == 1)
    {
        System.out.printf("\n%d --> %d", sourcePeg, destinationPeg);
        return;
    }

    //call the method itself
    solveTowers(disks - 1, sourcePeg, tempPeg, destinationPeg);

    System.out.printf("\n%d --> %d", sourcePeg, destinationPeg);

    solveTowers(disks - 1, tempPeg, destinationPeg, sourcePeg);
}

My question is what is the "return" for under the first System.out statement ?

When debugging, after the first solveTowers method reaches the base case, which the disk == 1, it goes into the if statement, then after reach the return;, it goes to the second System.out statement, then following by the second solveTowers method, so question is why the return; skipped the first solveTowers but not the second one ?

Upvotes: 0

Views: 463

Answers (4)

Neji
Neji

Reputation: 6839

when you have only 1 disk then it need to stop execution and thats why it outputs the source and destination and exits out.

Upvotes: 1

Renato Lochetti
Renato Lochetti

Reputation: 4566

This return; is saying that if you have just one disk, there is no need to do anything, so you just end the method's execution returning it. This is needed because the method is dealing with recursions and you must worry about the base case.

And since the method's return type is void, you don't need to return any value. So, just return;

Upvotes: 4

Timothy Groote
Timothy Groote

Reputation: 8652

The return statement ends the execution of the function or method once it is reached.

Since the return type of this method is void, it does not need to return a value in order to end the function, and can be called simply like this : return;

If the return type would have been different (for instance an integer), it would have to return an integer like this : return 1;

Upvotes: 4

Veger
Veger

Reputation: 37915

return is a Java statement that returns from the current method without executing any code that is following it.

In your case, the code checks if there is only one disk available, if so it just prints the solution and prevents the execution of the rest of the method.

Upvotes: 1

Related Questions