Write a C++ program to illustrate the concept of towers of hanoi problem.

Program Algorithm:
Step 1: Include the header files
Step 2: If n=1, move the disk from A to C
Step 3: If n=2, move the 1st disk from A to B then move the 2nd disk from A to C and finally move the 1st disk from B to C
Step 4: If n=3, repeat step 3 to move the first 2 disks from A to B using C as intermediate. Then the 3rd disk is moved from A to C. Then repeat step 3 to move 2 disks from B to C using A as intermediate.


Program Code in C++:
#include <iostream.h>
#include <conio.h>
void tower(int a,char from,char aux,char to)
{
if(a==1)
{
cout<<"\t\tMove disc 1 from "<<from<<" to "<<to<<"\n";
return;
}
else
{
tower(a-1,from,to,aux);
cout<<"\t\tMove disc "<<a<<" from "<<from<<" to "<<to<<"\n";
tower(a-1,aux,from,to);
}
}
void main()
{
clrscr();
int n;
cout<<"\n\t\t*****Tower of Hanoi*****\n";
cout<<"\t\tEnter number of discs : ";
cin>>n;
cout<<"\n\n";
tower(n,'A','B','C');
getch();
}


Program Output:
****Towers of Hanoi****
Enter number of disks: 2
Move disc 1 from A to B
Move disc 2 from A to C
Move disc 1 from B to C
Mukesh Rajput

Mukesh Rajput

I am a Computer Engineer, a small amount of the programming tips as it’s my hobby, I love to travel and meet people so little about travel, a fashion lover and love to eat food, I am investing a good time to keep the body fit so little about fitness also..

Post A Comment:

0 comments: