Saturday, February 20, 2016

STACK APPLICATION –TOWERS OF HANOI

AIM:
         To implement a C++ program to illustrate the concept of towers of hanoi problem
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:
#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();
}
SAMPLE 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

RESULT: Thus a C++ program to illustrate the concept of towers of hanoi problem is implemented successfully

No comments:

Post a Comment