Sunday, July 24, 2011

Algorithm of Tower of Hanoi Using c/c++

Number of disks having different diameter are placed on peg A so that larger disk always below a smaller disk.
       Source Code of Tower of Hanoi Using c/c++
**********************
Name :- Tower_of_Hanoi.cpp
IDE :- Codeblocks 10.05
**********************

#include <iostream>
using namespace std;
int n,a[10],b[10],c[10];
int *x=a,*y=b,*z=c;
void move(int n,int *a,int *c,int *b)
{
if(n==1)
{
c[n-1]=a[n-1];
cout<<"Move disk "<<a[n-1];
if(a==x) cout<<" from A ";
else if(a==y) cout<<" from B ";
else cout<<" from C ";
if(c==x) cout<<"to A ";
else if(c==y) cout<<"to B ";
else cout<<"to C ";
cout<<endl;
}
else
{
move(n-1,a,b,c);
c[n-1]=a[n-1];
cout<<"Move disk "<<a[n-1];
if(a==x) cout<<" from A ";
else if(a==y) cout<<" from B ";
else cout<<" from C ";
if(c==x) cout<<"to A ";
else if(c==y) cout<<"to B ";
else cout<<"to C ";
cout<<endl;
move(n-1,b,c,a);
}
}
int main()
{
cout<<"Enter the number of disks in TOH:";
cin>>n;
cout<<"Enter "<<n<<" numbers:"<<endl;
for(int i=0;i<n;i++)
cin>>a[i];
move(n,a,c,b);
cout<<"The numbers after transfering are:"<<endl;
for(int i=0;i<n;i++)
cout<<c[i]<<endl;
return 0;
}

No comments:

Post a Comment