C Program for Tower of Hanoi

Problem Description

Write a C program to solve the Tower of Hanoi Problem.

What is the Tower of Hanoi?

The Tower of Hanoi is a mathematical game or puzzle consisting of 3 rods or pegs and ‘n’ disks of varying diameters. It starts with all disks stacked on one rod in decreasing order. The objective is to move all these disks onto another rod.

Problem Solution

This C program uses a recursive function to solve the Tower of Hanoi puzzle. The Tower of Hanoi is a mathematical puzzle that consists of three rods and a number of disks of different sizes, which can slide onto any rod. The puzzle begins with all disks stacked on one rod in decreasing order of size, and the task is to move the entire stack to another rod, obeying the following rules:

Rules of Tower of Hanoi Puzzle:

  • Only one disk can be moved at a time.
  • Each move consists of taking the topmost disk from one of the stacks and placing it on top of another stack or on an empty rod.
  • No disk may be placed on top of a disk that is smaller than it.

Example:

Let’s consider a scenario where the number of disks is 4, and the starting rod is ‘A’, the auxiliary rod is ‘B’ and the ending rod is ‘C’.

Step-by-Step Process:

advertisement
advertisement

Initially, all disks are stacked on peg ‘A‘ in descending order of their size: Disk3 < Disk2 < Disk1

       Peg A                    Peg B                    Peg C
    
       Disc 3
       Disc 2
       Disc 1

Moving Disc 3 To Peg C:

       Peg A                    Peg B                    Peg C

       Disc 2
       Disc 1                                                  Disc 3

Moving Disc 2 To Peg B:

       Peg A                    Peg B                    Peg C
 
       Disc 1                    Disc 2                    Disc 3

Moving Disc 3 To Peg B:

Note: Join free Sanfoundry classes at Telegram or Youtube
       Peg A                    Peg B                    Peg C
  
                                     Disc 3
        Disc 1                   Disc 2

Moving Disc 1 To Peg C:

       Peg A                    Peg B                    Peg C
     
                                     Disc 3
                                     Disc 2                     Disc 1

Moving Disc 3 To Peg B:

       Peg A                    Peg B                    Peg C
 
       Disc 3                    Disc 2                    Disc 1

Moving Disc 2 To Peg C:

       Peg A                    Peg B                    Peg C
         
       Disc 3                                                  Disc 2
                                                                    Disc 1

Moving Disc 3 To Peg C:

       Peg A                    Peg B                    Peg C
      
                                                                    Disc 3
                                                                    Disc 2
                                                                    Disc 1

This final arrangement signifies the desired solution, where all disks are stacked on peg ‘C‘.

advertisement

The Tower of Hanoi problem is typically approached using recursion, calling a function twice to position disks on the desired pegs.

Tower of Hanoi Algorithm:

1. Start the program.
2. Input number of disks.
3. Define a function that takes the count of disks, initial disk, auxiliary disk, and target disk as arguments and recursively invokes itself twice.
4. Call the function.
5. End the Program.

Program/Source Code

Here is the source code of the C program for tower of hanoi. The C Program is successfully compiled and run on a Linux system. The program output is also shown below.

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

1. First input the number of disks placed on three rods.
2. Declare a function which takes 4 parameters which are: no of disks and name of initial disk, auxiliary disk and final disk.
3. The function recursively calls itself twice to solve the problem with a base case to stop when n is 1.
4. Call this function from main function.

advertisement

Time Complexity: O(2n)
In each function call, we are calling the function twice so time complexity of tower of hanoi program is O(2n).

Space Complexity: O(n)
Space of the recursive stack is of order n, so space complexity of tower of hanoi program is O(n).

Program Output

In this case, the user enters “3” as the number of discs as input to solve the Tower of Hanoi puzzle.

 
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

To practice programs on every topic in C, please visit “Programming Examples in C”, “Data Structures in C” and “Algorithms in C”.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). 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!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.