Saturday 22 March 2014

TOWER OF HANOI

This is a famous game for programmer .

Object of the game is to move all the disks over to tower C (final destination let say D )   from tower A (source tower let say S ) with the help of tower B (temporary Tower let say T) .

Condition :  But here is the twist,you cannot place a larger disk onto a smaller disk at any time during your moves.


But with a simple C program ,we can solve it.
This is also  an perfect example of recursion


C program:

  1.  /* Program for solution of Tower of Hanoi*/  
  2.  #include<stdio.h>  
  3.  #include<conio.h>  
  4.  void toh( int ndisk, char source, char temp, char dest )  
  5.  {  
  6.       if ( ndisk > 0 )  
  7.       {  
  8.            toh ( ndisk-1, source, dest, temp );
                                             //first move n-1 disks from source to temp
  9.            printf ( "Move Disk %d %c-->%c\n", ndisk, source,dest );  
  10.            toh( ndisk-1, temp, source, dest );
                                              //move remaining one disk to destination
  11.       }  
  12.  }/*End of toh()*/  
  13.  int main()  
  14.  {  
  15.       char source= 'S',temp= 'T', dest= 'D';  
  16.       int ndisk;  
  17.       printf("Enter the number of disks : "); //no. of disks
  18.       scanf ( "%d"&ndisk );  
  19.       printf ("Sequence is :\n");  
  20.       toh( ndisk, source, temp, dest );  //passing values to each argument
  21.       getch();  
  22.  }

  


OUTPUT:

thank you.................

No comments:

Post a Comment

THANKS FOR UR GREAT COMMENT

Blogger Widgets