C Program to Solve Tower-of-Hanoi Problem using Recursion

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.

  1. /*
  2.  * C program for Tower of Hanoi using Recursion
  3.  */
  4. #include <stdio.h>
  6. void towers(int, char, char, char);
  8. int main()
  9. {
  10.     int num;
  12.     printf("Enter the number of disks : ");
  13.     scanf("%d", &num);
  14.     printf("The sequence of moves involved in the Tower of Hanoi are :\n");
  15.     towers(num, 'A', 'C', 'B');
  16.     return 0;
  17. }
  18. void towers(int num, char frompeg, char topeg, char auxpeg)
  19. {
  20.     if (num == 1)
  21.     {
  22.         printf("\n Move disk 1 from peg %c to peg %c", frompeg, topeg);
  23.         return;
  24.     }
  25.     towers(num - 1, frompeg, auxpeg, topeg);
  26.     printf("\n Move disk %d from peg %c to peg %c", num, frompeg, topeg);
  27.     towers(num - 1, auxpeg, topeg, frompeg);
  28. }

$ 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.


Here’s the list of Best Reference Books in C Programming, Data-Structures and Algorithms

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!
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer & SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage, Advanced C Programming, SAN Storage Technologies, SCSI Internals & Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him @ LinkedIn | Youtube | Instagram | Facebook | Twitter