Here is a C++ program to solve Tower of Hanoi
SOURCE CODE OUTPUT
#include<iostream>
#include<math.h>
using namespace std;
void tower(char from,char aux,char to,int n)
{
if(n==1)
{
cout<<"Move disk "<<n<<" from peg "<<from<<" to peg "<<to<<endl;
return ;
}
tower(from,to,aux,n-1);
cout<<"Move disk "<<n<<" from peg "<<from<<" to peg "<<to<<endl;
tower(aux,from,to,n-1);
}
int main()
{
int n;
cout<<"Enter numbers of disk : ";
cin>>n;
tower('A','B','C',n);
return 0;
}
#include<math.h>
using namespace std;
void tower(char from,char aux,char to,int n)
{
if(n==1)
{
cout<<"Move disk "<<n<<" from peg "<<from<<" to peg "<<to<<endl;
return ;
}
tower(from,to,aux,n-1);
cout<<"Move disk "<<n<<" from peg "<<from<<" to peg "<<to<<endl;
tower(aux,from,to,n-1);
}
int main()
{
int n;
cout<<"Enter numbers of disk : ";
cin>>n;
tower('A','B','C',n);
return 0;
}
Any questions regarding to program please write in comments.
No comments:
Post a Comment