Nov 18, 2010

C Program for Tower of Hanoi

#include<conio.h>
#include<iostream.h>
class tower
{
int nodisk;
char frmtwr,totwr,auxtwr;
public:
void hanoi(int,char,char,char);
};

void tower::hanoi(int nodisk,char frmtwr,char totwr,char auxtwr)
{
if (nodisk==1)
{
cout<<"\nMove disk 1 from tower "<<frmtwr<<" to tower "<<totwr;
return;
}
hanoi(nodisk-1,frmtwr,auxtwr,totwr);
cout<<"\nMove disk "<<nodisk<<" from tower "<<frmtwr<<" to tower "<<totwr;
hanoi(nodisk-1,auxtwr,totwr,frmtwr);
return;
}

void main()
{
int no;
tower ob;
clrscr();
cout<<"\n\t\t\t\t--- Tower Of Hanoi ---\n";
cout<<"\n\t\t\t--- (assuming towers X, Y & Z) ---\n";
cout<<"\n\nEnter the number of disks: ";
cin>>no;
ob.hanoi(no,'X','Y','Z');
cout<<"\n\nPress any key to continue...";
getch();
}

0 comments:

Post a Comment