javatowers-of-hanoi

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 ?


Solution

  • 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;