Tower of Hanoi in C
Advertisements
Tower of Hanoi in C
Tower of Hanoi is a mathematical puzzle where we have three rods and n disks. The main objective of tower of hanoi puzzle is to move the entire stack to another rod.
Rules to follow
- Only one disk can be moved at a time.
- Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack.
- No disk may be placed on top of a smaller disk.
Tower of Hanoi Program in C
#include<stdio.h> #include<conio.h> #include<math.h> void hanoi(int x, char beg,char end,char aux) { if(x==1) { printf("Move Disk From %c to %c\n",beg,end); } else { hanoi(x-1,beg,aux,end); printf("Move Disk From %c to %c\n",beg,end); hanoi(x-1,aux,end,beg); } } void main() { int disk; int moves; clrscr(); printf("Enter the number of disks you want to play with: "); scanf("%d",&disk); moves=pow(2,disk)-1; //FIND THE NO. OF MOVES printf("\nThe No of moves required is: %d \n",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 B to A Move Disk From B to C Move Disk From A to C
Note: Download above code and de-compress zip file, after that you can easily run this code.
Google Advertisment