Tower of Hanoi in C++

Implementation of Tower of Hanoi problem.

Source code :


#include <iostream>

using namespace std;

void toh(int,char,char,char);


void toh(int n, char fromspindle, char tospindle, char tempspindle )
{
    if (n == 1)
    {
        cout<<"\nMove disk 1 from spindle "<< fromspindle <<" to spindle "<< tospindle;
        return;
    }
    
    toh(n-1, fromspindle, tempspindle, tospindle);
    cout<< "\nMove disk "<< n <<" from spindle "<< fromspindle <<" to spindle "<< tospindle;
    toh(n-1, tempspindle, tospindle, fromspindle);
	
}

int main()
{
    int n = 4; // Total number of disks
    toh(n, 'A', 'C', 'B'); //  Name of the spindles
    return 0;
}

Output :

Move disk 1 from spindle A to spindle B
Move disk 2 from spindle A to spindle C
Move disk 1 from spindle B to spindle C
Move disk 3 from spindle A to spindle B
Move disk 1 from spindle C to spindle A
Move disk 2 from spindle C to spindle B
Move disk 1 from spindle A to spindle B
Move disk 4 from spindle A to spindle C
Move disk 1 from spindle B to spindle C
Move disk 2 from spindle B to spindle A
Move disk 1 from spindle C to spindle A
Move disk 3 from spindle B to spindle C
Move disk 1 from spindle A to spindle B
Move disk 2 from spindle A to spindle C
Move disk 1 from spindle B to spindle C

Output :


                

Comments :