Tower_of_Hanoi

#include <iostream> #include <cmath> using namespace std; bool confirm() { char ch = '\o'; while (ch != 'y' && ch != 'Y' && ch != 'n' && ch != 'N') cin >> ch; if (ch == 'y' || ch == 'Y') return true; else return false; } void hanoi(int n, char A, char B, char C) { if (n == 1) { cout << "[Disk: 1]\t" << A << " -> " << B << endl; return; } else { hanoi(n - 1, A, C, B); cout << "[Disk: " << n << "]\t" << A << " -> " << B << endl; hanoi(n - 1, C, B, A); } } int main() { int n; cout << "Enter the Number of Disks: "; cin >> n; cout << "Number of Swaps: " << pow(2, n) - 1 << endl; cout << "Do you want to Display the Swaps? (y/n): "; if (confirm()) hanoi(n, 'A', 'B', 'C'); //initially all the Disks are on Tower A cout << endl << "Exiting..." << endl; return 0; }

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.