How to Play:
To play the Towers of Hanoi game, you must move the discs from peg A to peg B by moving one disc at a time. A larger disc can never sit atop a smaller disc. Peg C can be used as a holding area.
In the true problem, there are a total of 64 discs.
|
The number of moves needed to solve the game, based upon the number of discs in the game, can be expressed recursively.
Here is the source code of the C program for solving towers of hanoi. The C Program is successfully compiled and run on a Linux system. The program output is also shown below.
#include <stdio.h>
#include <conio.h>
void towers(int, char, char, char);
int main()
{
int num;
clrscr();
printf("Enter the number of disks : ");
scanf("%d", &num);
printf("The sequence of moves involved in the Tower of Hanoi are :\n");
towers(num, 'A', 'C', 'B');
getch();
return 0;
}
void towers(int num, char frompeg, char topeg, char auxpeg)
{
if (num == 1)
{
printf("\n Move disk 1 from peg %c to peg %c", frompeg, topeg);
return;
}
towers(num - 1, frompeg, auxpeg, topeg);
printf("\n Move disk %d from peg %c to peg %c", num, frompeg, topeg);
towers(num - 1, auxpeg, topeg, frompeg);
}