Tower of Hanoi in C++
Solve Tower of Hanoi in C++ with recursion: the three-step idea, how the peg parameters swap, a full move list for 3 disks, and why it takes 2^n − 1 moves.
1#include <iostream>2using namespace std;34void towerOfHanoi(int n, char from, char to, char aux) {5 // Base case6 if (n == 1) {7 cout << "Move disk 1 from " << from << " to " << to << endl;8 return;9 }1011 // Move n-1 disks from 'from' to 'aux' using 'to' as auxiliary12 towerOfHanoi(n - 1, from, aux, to);1314 // Move the largest disk from 'from' to 'to'15 cout << "Move disk " << n << " from " << from << " to " << to << endl;1617 // Move n-1 disks from 'aux' to 'to' using 'from' as auxiliary18 towerOfHanoi(n - 1, aux, to, from);19}2021int main() {22 int n;23 cout << "Enter number of disks: ";24 cin >> n;2526 cout << "\nTower of Hanoi solution:" << endl;27 cout << "Moving " << n << " disks from A to C using B as auxiliary\n" << endl;2829 towerOfHanoi(n, 'A', 'C', 'B');3031 // Calculate total moves32 int totalMoves = (1 << n) - 1; // 2^n - 133 cout << "\nTotal moves required: " << totalMoves << endl;3435 return 0;36}
Sample Output
Move disk 3 from A to C
The largest disk moves once, in the middle.
Total moves required: 7
2³ − 1.
In this one
- The three-step recursive plan
- How swapping parameters picks the spare peg
- Why the move count is 2ⁿ − 1
- How 1 << n computes a power of two
How it works
- 1
Read n.
- 2
towerOfHanoi(n, A, C, B).
- 3
Move n − 1 disks A→B, move disk n A→C, move n − 1 disks B→C.
- 4
Print the total, (1 << n) − 1.
Dry run: Tower of Hanoi
n = 2, A→C using B
- 1.hanoi(1, A, B, C): Move disk 1 from A to B
- 2.Move disk 2 from A to C
- 3.hanoi(1, B, C, A): Move disk 1 from B to C
- 4.3 moves = 2² − 1
n = 2, A→C using B hanoi(1, A, B, C): Move disk 1 from A to B Move disk 2 from A to C hanoi(1, B, C, A): Move disk 1 from B to C 3 moves = 2² − 1
Edge cases
n = 0
Enter 0.
The base case never matches, so the recursion runs into negatives and crashes with a stack overflow. Add if (n == 0) return; or reject it in main.
Large n
Enter 25.
The program prints 33,554,431 lines. The recursion depth is only 25, but the output takes a long time.
n ≥ 31
Enter 31.
1 << 31 overflows a 32-bit int, so the total is wrong. Use 1LL << n.
What's going on
Tower of Hanoi has three pegs, A, B, and C, and n disks stacked on A from largest at the bottom to smallest on top. The goal is to move the stack to C. You can move one disk at a time, and a larger disk may never sit on a smaller one.
The recursive idea fits in three steps. To move n disks from A to C:
Steps 1 and 3 are the same problem with one fewer disk, so the function calls itself for them. The base case is one disk, which just moves.
towerOfHanoi(n, from, to, aux) follows those steps exactly. The parameter order is what changes between calls: the first call swaps to and aux, and the second swaps from and aux.
For 3 disks the output lists 7 moves. Disk 3, the largest, moves exactly once, in the middle. Disk 2 moves twice and disk 1 moves four times.
The total is always 2ⁿ − 1 moves, which (1 << n) - 1 computes: shifting 1 left by n places is 2ⁿ. The count doubles with each disk, so 20 disks need over a million moves and 64 disks would take longer than the age of the universe at one move a second.
Input 0 is not handled. The base case is n == 1, so towerOfHanoi(0, ...) calls itself with −1, −2, and so on until the stack overflows. A base case of if (n == 0) return; would cover it.
The headers come first. <iostream> is there because it provides cout and cin for input/output operations. Leave one out and the compiler stops at the first name it does not recognize.
Understanding Tower of Hanoi
Problem Statement:
Goal:
Recursive Algorithm
Divide-and-Conquer Strategy:
What happens here:
Base Case
Single Disk:
if (n == 1) {
cout << "Move disk 1 from " << from << " to " << to << endl;
return;
}
What happens here:
Recursive Case
Three Steps:
What happens here:
Minimum Moves
Formula:
Total moves = 2^n - 1
What happens here:
Time Complexity
Analysis:
Space Complexity:
When to Use This Algorithm
Good fits:
Not Practical For:
Important Considerations
Recursive Structure:
Exponential Growth:
Problem-Solving:
return 0;
return 0; closes main and tells the operating system the program finished without an error.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
How many moves for 4 disks?
Pick an answer to check it.
Question 2
In the first recursive call, which peg is the spare?
Pick an answer to check it.
Questions people ask
Is there a loop solution?
Yes. An iterative version alternates moving the smallest disk in a fixed direction with the only other legal move.
Why does disk 1 move so often?
It moves on every other turn: 2ⁿ⁻¹ times in total.
What does the recursion depth reach?
n, because each call reduces n by one before calling again.