Friday, 24 July 2015

C++ Program to Solve Tower-of-Hanoi Problem using Recursion

Leave a Comment
This C++ Program uses recursive function & solves the tower of hanoi. The tower of hanoi is a mathematical puzzle. It consists of threerods, and a number of disks of different sizes which can slideonto 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. We have to obtain the same stack on the third rod.

Here is the source code of the C program for solving towers of hanoi.


using namespace std;

void towers(int, char, char, char);

int main()
    int num;

    cout<<"Enter the number of disks : ";
    cout<<"The sequence of moves involved in the Tower of Hanoi are :\n";
    towers(num, 'A', 'C', 'B');
    return 0;

void towers(int num, char frompeg, char topeg, char auxpeg)
    if (num == 1)
        cout<<"\n Move disk 1 from peg"<<frompeg<<"to peg "<< topeg;
    towers(num - 1, frompeg, auxpeg, topeg);
    cout<<"\n Move disk "<<num<<"from peg"<<frompeg<<" to peg "<<topeg;
    towers(num - 1, auxpeg, topeg, frompeg);



If You Enjoyed This, Take 5 Seconds To Share It