This C Program uses recursive function & solves the tower of hanoi. The tower of hanoi is a mathematical puzzle. It consists of threerods, and a number of disks of different sizes which can slideonto 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. We have to obtain the same stack on the third rod.
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.
* C program for Tower of Hanoi using Recursion
void towers(int, char, char, char);
printf("Enter the number of disks : ");
printf("The sequence of moves involved in the Tower of Hanoi are :\n");
towers(num, 'A', 'C', 'B');
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);
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);
$ cc pgm11.c $ a.out Enter the number of disks : 3 The sequence of moves involved in the Tower of Hanoi are : Move disk 1 from peg A to peg C Move disk 2 from peg A to peg B Move disk 1 from peg C to peg B Move disk 3 from peg A to peg C Move disk 1 from peg B to peg A Move disk 2 from peg B to peg C Move disk 1 from peg A to peg C
Sanfoundry Global Education & Learning Series – 1000 C Programs.
If you wish to look at other example programs on Puzzles & Games, go to Puzzles & Games. If you wish to look at programming examples on all topics, go to C Programming Examples.Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!