Tower of Hanoi Program in C/C++

The Tower of Hanoi (also called the Tower of Brahma or Lucas' Tower, and sometimes pluralised) is a mathematical game or puzzle. It consists of three rods, and a number of disks of different sizes which can slide onto any rod. The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the smallest at the top, thus making a conical shape.
The objective of the puzzle is to move the entire stack to another rod, obeying the following rules:
  • Only one disk may be moved at a time.
  • Each move consists of taking the upper disk from one of the rods and sliding it onto another rod, on top of the other disks that may already be present on that rod.
  • No disk may be placed on top of a smaller disk.
With three disks, the puzzle can be solved in seven moves.



below is the best implementation of Tower of Hanoi Program in C.
Do subscribe to this blog to get the latest updates.
Tell me what you think about this program in comments.


#include<stdio.h>
#include<conio.h>
#include<math.h>
 
void hanoi(int xchar fromchar tochar aux)
{
 if (x == 1)
 {
  printf("Move Disk From %c to %c\n"fromto);
 }
 else
 {
  hanoi(x - 1, fromauxto);
  printf("Move Disk From %c to %c\n"fromto);
  hanoi(x - 1, auxtofrom);
 }
}
 
int main(void)
{
 int disk;
 double moves;
 clrscr();
 printf("Enter the number of disks you want to play with:");
 scanf("%d", &disk);
 moves = pow(2, disk) - 1;
 printf("\nThe No of moves required is=%g \n", moves);
 hanoi(disk, 'A''C''B');
 getch();
}

1 comments :

Have a look here for explanation
http://clanguagestuff.blogspot.in/2013/09/tower-of-hanoi.html

Reply

Post a Comment