Tower of Hanoi C++ Program

In this program I will give you information about tower of hanoi c++ program with the help of explanation. In the given below code we are using recursion.

Code For Tower of Hanoi C++ Program

#include <iostream>
using namespace std;
// Function prototype
void towerOfHanoi(int num_disks, char source_rod, char destination_rod, char auxiliary_rod);

int main()
{
    int num_disks; // number of disks

    std::cout << "Enter the number of disks: ";
    std::cin >> num_disks;

    // solve the puzzle
    towerOfHanoi(num_disks, 'A', 'C', 'B');

    return 0;
}

// Recursive function to solve Tower of Hanoi puzzle
void towerOfHanoi(int num_disks, char source_rod, char destination_rod, char auxiliary_rod)
{
    if (num_disks == 1)
    {
        std::cout << "Move disk 1 from rod " << source_rod << " to rod " << destination_rod << std::endl;
        return;
    }
    towerOfHanoi(num_disks - 1, source_rod, auxiliary_rod, destination_rod);
    std::cout << "Move disk " << num_disks << " from rod " << source_rod << " to rod " << destination_rod << std::endl;
    towerOfHanoi(num_disks - 1, auxiliary_rod, destination_rod, source_rod);
}

Explanation:

The Tower of Hanoi is a puzzle that involves three rods and a set of disks of different sizes. The puzzle starts with the disks in a stack in ascending order of size on one rod, with the smallest at the top. The goal is to move the entire stack to another rod, following these rules:

  • Only one disk can be moved at a time.
  • A disk can only be moved if it is the topmost disk on a stack.
  • A larger disk cannot be placed on top of a smaller disk.

This program uses a recursive function, towerOfHanoi(), to solve the puzzle. The function has four parameters:

  • num_disks: the number of disks
  • source_rod: the rod where the disks are initially located
  • destination_rod: the rod where the disks should be moved to
  • auxiliary_rod: an additional rod that can be used as temporary storage

The base case of the recursion occurs when num_disks is equal to 1. In this case, we simply print the step to move the disk from the source rod to the destination rod.

Otherwise, we move num_disks - 1 disks from the source rod to the auxiliary rod, using the destination rod as temporary storage. Then, we move the num_disksth disk from the source rod to the destination rod. Finally, we move the num_disks - 1 disks from the auxiliary rod to the destination rod, using the source rod as temporary storage.

I hope this helps! Let me know if you have any questions.

Also Read: C++ program for multilevel inheritance


If You Like This Page Then Make Sure To Follow Us on Facebook, G News and Subscribe Our YouTube Channel. We will provide you updates daily.
Shares
facebook sharing button Share
twitter sharing button Tweet
whatsapp sharing button Share
telegram sharing button Share
pinterest sharing button Pin

Leave a Comment