ISC Practicals and Theory - Tower of Hanoi (Recursive Technique) (OOP)
Updated 20 Oct 2026
This version of the Tower of Hanoi is written as a class: an object stores the number of disks, a parameterised constructor sets it up, and each method does one job. The solving method hanoi() calls itself, so the recursion is the core of the program. It prints every move and compares the number of moves with $2^n - 1$.
Definition
Three pegs hold disks of different sizes, largest at the bottom. All $n$ disks start on peg A and must reach peg C, using B as a spare. One disk moves at a time, only a top disk can move, and a larger disk is never put on a smaller one. The minimum number of moves is $2^n - 1$, for example $2^2 - 1 = 3$ for two disks.
The program accepts $n$ from 1 to 10. Every move is printed, so $n = 10$ prints $2^{10} - 1 = 1023$ moves; the sample runs below use small values of $n$ to keep the output short.
Algorithm
mainreadsnum, creates the objecttwithnew TowerOfHanoi(num); the constructor stores it innand setsmovesto 0.isValid()returnstrueonly whennis from 1 to 10. If it returnsfalse,mainprints an error and nothing else runs.hanoi(d, from, to, via)does the recursion:- If
d == 0there is nothing to move, so it returns (base case). - Call
hanoi(d - 1, from, via, to)to move the topd - 1disks to the spare peg. - Add 1 to
movesand printMove disk d from <from> to <to>. - Call
hanoi(d - 1, via, to, from)to bring thed - 1disks onto diskd.
- If
formula()finds $2^n - 1$ with a loop that doubles a valuentimes, withoutMath.pow.showTotal()printsmovesandformula(); they must be equal.
Program
The constructor stores the number of disks, isValid() checks the range, hanoi() is the recursive method, formula() computes $2^n - 1$ and showTotal() prints both totals.
import java.util.Scanner;
/**
* Class TowerOfHanoi: an object holds a puzzle with n disks and solves it recursively.
*/
public class TowerOfHanoi
{
int n; // number of disks in the puzzle
int moves; // number of moves made so far
/**
* Parameterised constructor.
* @param nn number of disks to store in n
*/
TowerOfHanoi(int nn)
{
n = nn;
moves = 0; // no move made yet
}
/**
* Checks whether the number of disks is in the allowed range 1 to 10.
* @return true if 1 <= n <= 10, otherwise false
*/
boolean isValid()
{
return n >= 1 && n <= 10;
}
/**
* Recursive method: moves d disks from peg 'from' to peg 'to' using peg 'via',
* printing every move.
* @param d number of disks to move
* @param from the peg the disks start on
* @param to the peg the disks must reach
* @param via the spare peg used for help
*/
void hanoi(int d, char from, char to, char via)
{
if (d == 0) // base case: no disk to move, so stop
return;
hanoi(d - 1, from, via, to); // d-1 disks go from 'from' to the spare peg
moves++; // count the move of disk d
System.out.println("Move disk " + d + " from " + from + " to " + to);
hanoi(d - 1, via, to, from); // d-1 disks go from the spare peg to 'to'
}
/**
* Calculates 2^n - 1 with a loop, without Math.pow.
* @return the minimum number of moves for n disks
*/
int formula()
{
int p = 1;
for (int i = 1; i <= n; i++) // multiply by 2, n times
p = p * 2;
return p - 1;
}
/** Prints the moves counted by the recursion and the value of 2^n - 1. */
void showTotal()
{
System.out.println("Total number of moves = " + moves);
System.out.println("2^n - 1 = " + formula());
}
/**
* main: reads n, creates the object and calls the methods.
* @param args command line arguments (not used)
*/
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in); // Scanner for input
System.out.print("Enter the number of disks (1 to 10): ");
int num = sc.nextInt(); // number of disks typed by the user
TowerOfHanoi t = new TowerOfHanoi(num); // object of the class
if (t.isValid())
{
t.hanoi(num, 'A', 'C', 'B');
t.showTotal();
}
else
System.out.println("Invalid input. Number of disks must be from 1 to 10.");
}
}Variable description table
| Variable | Data Type | Purpose |
|---|---|---|
n | int | Data member: number of disks in the puzzle |
moves | int | Data member: number of moves made so far |
nn | int | Parameter of the constructor: number of disks, copied to n |
d | int | Parameter of hanoi: number of disks to move in this call |
from | char | Parameter of hanoi: peg the disks start on |
to | char | Parameter of hanoi: peg the disks must reach |
via | char | Parameter of hanoi: spare peg used for help |
p | int | Local in formula: holds the power of 2, ending as $2^n$ |
i | int | Loop counter in formula |
args | String[] | Command line arguments of main (not used) |
sc | Scanner | Scanner object connected to the keyboard |
num | int | Number of disks typed by the user |
t | TowerOfHanoi | Object of the class, used to call the methods |
Sample input and output
Sample 1
Enter the number of disks (1 to 10): 2
Move disk 1 from A to B
Move disk 2 from A to C
Move disk 1 from B to C
Total number of moves = 3
2^n - 1 = 3Sample 2
Enter the number of disks (1 to 10): 3
Move disk 1 from A to C
Move disk 2 from A to B
Move disk 1 from C to B
Move disk 3 from A to C
Move disk 1 from B to A
Move disk 2 from B to C
Move disk 1 from A to C
Total number of moves = 7
2^n - 1 = 7Sample 3
Enter the number of disks (1 to 10): 0
Invalid input. Number of disks must be from 1 to 10.Dry run
Input: num = 2. main calls t.hanoi(2, 'A', 'C', 'B'). Calls are numbered in the order they start. This void method returns nothing, so what carries back up is the running value of moves.
| Call | d | from | to | via | Action | moves |
|---|---|---|---|---|---|---|
| 1 | 2 | A | C | B | calls call 2 | 0 |
| 2 | 1 | A | B | C | calls call 3 | 0 |
| 3 | 0 | A | C | B | base case, returns | 0 |
| 2 (resumes) | 1 | A | B | C | prints Move disk 1 from A to B, calls call 4 | 1 |
| 4 | 0 | C | B | A | base case, returns | 1 |
| 1 (resumes) | 2 | A | C | B | prints Move disk 2 from A to C, calls call 5 | 2 |
| 5 | 1 | B | C | A | calls call 6 | 2 |
| 6 | 0 | B | A | C | base case, returns | 2 |
| 5 (resumes) | 1 | B | C | A | prints Move disk 1 from B to C, calls call 7 | 3 |
| 7 | 0 | A | C | B | base case, returns | 3 |
Call 5 returns to call 1, which returns to main. showTotal() prints Total number of moves = 3, and formula() takes p through $1 \to 2 \to 4$, giving $4 - 1 = 3$. This matches the real run for input 2 above.
Variations
- Count only "Write a program to find the number of moves needed to shift n disks in the Tower of Hanoi, without printing the moves."
- Peg names "Accept the names of the three pegs from the user and print the moves using those names."
- Return the count "Write a recursive method that returns the number of moves for n disks."