Your Ad Here

Thursday, February 26, 2009

Write a C++ program that uses a recursive function for solving Towers of Hanoi problem.

#include(iostream.h) // place this '<' & '>' instead of '(' & ')' before iostream.h
#include(conio.h)
#include(math.h)
void hanoi(int x, char from, char to, char aux)
{
if(x==1)
cout<<"Move Disk From"<< from <<"to"<< to;
else
{
hanoi(x-1,from,aux,to);
cout<<"Move Disk From"<< from <<"to"<< to;
}
}
void main( )
{
int disk;
int moves;
clrscr();
cout<<"Enter the number of disks you want to play with:";
cin>>disk;
moves=pow(2,disk)-1;
cout<<"The No of moves required is:" << moves;
hanoi(disk,'A','C','B');
getch( );
}

Output:-
Enter the number of disks you want to play with: 3

The No of moves required is=7
Move Disk from A to C
Move Disk from A to B
Move Disk from C to B
Move Disk from A to C
Move Disk from B to A
Move Disk from B to C
Move Disk from A to C

Note:- If u have any doubt regarding this program or logic, please feel free to contact me.

No comments:

Post a Comment