C++

C++ Program for Tower of Hanoi using Recursion4 min read

Tower of Hanoi is a very old problem. People had been solving it for many years. In this problem, you have to shift disk from one peg to another peg using the third peg. Let me explain it more.

The set up of the problem is like in the above picture. There will be three pegs and every peg has its own name as the first peg is named “source” and the second peg is named “destination” and the third peg named as “via”. Now, these named suggest there work. Ā You have to shift all the disks from source to destination using the via a peg. Now you might be thinking this is the easiest problem you have heard off, you can just pick all the disks and put it in the destination peg without using any third peg. But it’s not that simple because there is catch here, you can move one disk at a time and no larger disk can be above the smaller disk while performing shifting. Now the problem becomes a little tricky.




Many people had tried this problem with a different number of disks and some succeed and some not. Some take more number of moves to solve and some take less.

So, I have made this project on the tower of Hanoi in which first it takes the input of the number of disks and then it gives the output in which it displays the order in which the disks are being moved.

 

I have used the concept of Recursion in this project which is very important to solve the problem of the tower of Hanoi. I have made a method called tower which is a recursive method. In the parameters of this method I have provided the number of disks and source and destination and via a peg.

Inside this method, we have two cases one is base and other is the recursive case. In base case, we just print which ring is moving from which peg to which peg using some peg.

In recursive case we use the method two times and in between them we print the message again.

So now the recursive method is ready to use in the main method. In the main method, we assign the different pegs value and takes the input of the number of rings and then calling the tower method, which does all the work.

C++ Code:

Output:

 

Leave a Comment