Solution for Tower of Hanoi C++

What is Tower of Hanoi?

All must be well aware of the problem of Tower of Hanoi, for those who don’t know, let’s discuss it once again.

The Tower of Hanoi (also called the Tower of Brahma or Lucas’ Tower, and sometimes pluralized) is a mathematical game or puzzle.


tower of hanoi


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:

  • Only one disk can be moved at a time.
  • 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.
  • No disk may be placed on top of a smaller disk.

Animated Solution:


tower of hanoi solution


 We can solve it in 2 ways:

  1. Using Recursion
  2. Using Stacks

Using Recursion:

Sample Output:


Program to solve Tower of Hanoi C++ using Stack

Sample Output:


  1. //
    //corrected by James H H Rodríguez
    using namespace std;
    void towers(int, char, char, char);
    void towers(int num, char frompeg, char topeg, char auxpeg)
    if (num == 1)
    cout<<" Move disk 1 from peg "<<frompeg<<" to peg "<<topeg<< endl;
    towers(num – 1, frompeg, auxpeg, topeg);
    cout<<" Move disk "<<num<<" from peg "<<frompeg<<" to peg "<<topeg<< endl;
    //cout << " Move disk " << n << " from " << src << " to " << dest << endl;
    towers(num – 1, auxpeg, topeg, frompeg);
    int main()
    int num;
    towers(num, ‘A’, ‘C’, ‘B’);
    return 0;

  2. Enter the mumber or disks : 3
    Move disk 1 from SRC to DEST
    Move disk 2 from SRC to AUX
    Move disk 1 from DEST to AUX
    Move disk 3 from SRC to DEST
    Move disk 1 from AUX to SRC
    Move disk 2 from AUX to DEST
    Move disk 1 from SRC to DEST
    Presione una tecla para continuar . . .

  3. I am need to implement tours of hanoi
    without recursion

  4. how this code will executed… about tracing?

  5. how to trace this code??

  6. meghana kaku says:

    how can we get ouput as “invalid input” on entering a negative number(eg -8) in towers of hanoi using recurrsion