Tower of Hanoi in C

Advertisements

Selection Sort in C Quick Sort in C

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

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
tower of hanoi in c

Note: Download above code and de-compress zip file, after that you can easily run this code.


Selection Sort in C Quick Sort in C

Google Advertisment

Buy This Ad Space @$20 per Month, Ad Size 600X200 Contact on: hitesh.xc@gmail.com or 9999595223

Magenet is best Adsense Alternative here we earn $2 for single link, Here we get links ads. Magenet

For Projects 9999595223

Google Advertisements


Buy Websites 9999595223

Buy College Projects with Documentation Contact on whatsapp 9999595223. Contact on: hitesh.xc@gmail.com or 9999595223 Try this Keyword C++ Programs

Advertisements