Tower of Hanoi Gaming Project in C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
#include <iostream> using namespace std; // Function to solve the Tower of Hanoi puzzle void towerOfHanoi(int n, char fromRod, char toRod, char auxRod) { if (n == 1) { cout << "Move disk 1 from rod " << fromRod << " to rod " << toRod << endl; return; } towerOfHanoi(n - 1, fromRod, auxRod, toRod); cout << "Move disk " << n << " from rod " << fromRod << " to rod " << toRod << endl; towerOfHanoi(n - 1, auxRod, toRod, fromRod); } int main() { int n; cout << "Enter the number of disks: "; cin >> n; cout << "The sequence of moves to solve the Tower of Hanoi puzzle is:" << endl; towerOfHanoi(n, 'A', 'C', 'B'); // A, B and C are names of rods return 0; } |
Explanation Tower of Hanoi Function: towerOfHanoi(int n, char fromRod, char toRod, char auxRod): This recursive function solves the Tower of Hanoi puzzle. Parameters: n: The number of disks to move. fromRod: The rod from which the disks are moved. toRod: The rod to which the disks are moved. auxRod: The auxiliary rod used in …