Implementing Tower of Hanoi Problem in Java

The Tower of Hanoi is a mathematical game or puzzle. It consists of three rods, and a number of disks of different sizes which can slide onto any rod. The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the smallest at the top, thus making a conical shape.

The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules:

  1. Only one disk can be moved at a time.
  2. Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack.
  3. No disk may be placed on top of a smaller disk.

With three disks, the puzzle can be solved in seven moves. The minimum number of moves required to solve a Tower of Hanoi puzzle is 2n – 1, where n is the number of disks.

(Via Wikipedia)

Here is java implementation of this problem. The program takes count of pegs as input and displays the steps to be followed to solve the problem.

public class TowersOfHanoi 
    public static int count=0;
    public static void main(String[] args) throws IOException
        BufferedReader obj= new BufferedReader(new InputStreamReader(;
        int n;
        System.out.println("Enter no of pegs:");
        System.out.println("No of steps :"+count);
    static void hanoi(int n,char from,char to,char aux)
             System.out.println("Move Disk 1 From "+from+" To "+to);
            System.out.println("Move disk "+n +" From "+from+" To "+to);

/* Output
Enter no of pegs:
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
No of steps :7

Leave a Reply

Your email address will not be published. Required fields are marked *