Previous Page

The Tower of Hanoi - C++ console

Copy and Paste the following code into your favorite C++ Integrated Development Environment (IDE) - compile and run.

/*
Brian Butler

This is the Tower of Hanoi - using recursion

Go to the following site for more info:

http://en.wikipedia.org/wiki/Tower_of_Hanoi

*/

#include <iostream>
#include <string>

using namespace std;

    int n;
    int num =1;

void moveDisks(int n, string pegOne, string pegTwo, string pegThree);

    int main()
    {

        cout << "Enter the number of disks to move from peg 1 to peg 3: ";

        cin >> n;

        endl (cout);

        moveDisks(n, "peg one", "peg two", "peg three");

        return 0;
    }
    
    
    void moveDisks(int n, string pegOne, string pegTwo, string pegThree)
    {
        if(n > 0)
        {

            moveDisks(n-1, pegOne, pegThree, pegTwo);

            cout << "Move #" <<  num << ": disk " << n <<" is moved from " << pegOne
                 << " to " << pegThree << endl;

            num++;

            moveDisks(n-1, pegTwo, pegOne, pegThree);
        }
    }

//END OF CODE