Answer:
follwing is the code for Tower of Hanoi for n disks.
#include <iostream>
using namespace std;
void towofhan(int n,char source,char aux,char dest)//function for tower of hanoi..
{
if(n<0)
return ;
if(n==1)//base case.
{
cout<<"Move disk 1 from "<<source<<" to spindle "<<dest<<endl;
return;
}
towofhan(n-1,source,dest,aux);//recursive call.
cout<<"move disk "<<n<<" from "<<source<<" to spindle "<<dest<<endl;
towofhan(n-1,aux,source,dest);//recursive call.
}
int main() {
int n=4;
towofhan(n,'1','2','3');//function call.
return 0;
}
Step-by-step explanation:
If there is only 1 disk then we have to move the disk from source to destination.
Then after that we will apply recursion to solve the problem.
We have to work on only nth disk else will be done by the recursion.
First call recursion to move n-1 disks from source to auxiliary.
Then move nth disk from source to destination spindle.
Now move n-1 disks that are on the auxiliary spindle to destination spindle.