Summary: In this tutorial, we will discuss how to solve the Tower of Hanoi problem in C using recursion.

What is the Tower of Hanoi?

Tower of Hanoi is a game where a certain number of disks of different sizes residing on a particular rod needs to be transferred into the final rod with the help of other available rods. But there is some condition:

  1. One Disk at a time is allowed for shifting.
  2. Large Disk cannot be put over smaller disk.

Following is the initial condition of Tower of Hanoi:

Tower of Hanoi in C

Following is the final solution to Tower of Hanoi:

Tower of Hanoi using Recursion

Tower of Hanoi in C using Recursion

To solve the Tower of Hanoi using Recursion, we need to understand a little trick and the concept of Recursion.

Recursive Algorithm to Solve Tower of Hanoi:

Suppose we are given 3 (n) disk as stated in the first diagram and asked to solve this using recursion. And we also know that putting a large disk over small ones is not allowed.

The trick is to assume that we are given only two disks (as stated in the picture).

C program to solve Tower of Hanoi

Now we need to shift the upper disk i.e n-1 (which actually contains 2 Disk in the current scenario) to B so that we can shift the last disk (n-th) to C.

The main point is we will not do this. The recursive function will take the responsibility to shift n-1 disks (2 disks in this case) to B.

where rodFrom = A , rodTo = B and rodMiddle = C will be used as auxiliary rod by the recursive function.

Tower of Hanoi algorithm

Now we need to shift the last disk (nth or largest disk) to rod C. So we will do this Just by outputting the statement.

where n=3, rodFrom = A and rodTo = C .

Tower of Hanoi recursion

Now again the n-1 disk (2 disks) in rod B need to be shifted to C with the help of rod A. Since there are multiple disk i.e n-1, so let the recursive function handle this task.

where rodFrom = B , rodTo = C and rodMiddle = A will be used as auxiliary rod by the recursive function.

Finally, the Tower of Hanoi is solved.

Tower of Hanoi using Recursion

Here, is the solution to the Tower of Hanoi in C.

Output

C program to solve Tower of Hanoi Problem

We have shown you the solution of 3 disk’s Tower of Hanoi problem in C.

The above program can be used to solve any number of Disks in the Tower of Hanoi game i.e any value of n. If you have doubts then comment below.

Leave a Reply