Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

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.

IntermediateRecursion ProgramsExample 3 of 5
tower-of-hanoi.cpp
1#include <iostream>
2using namespace std;
3
4void towerOfHanoi(int n, char from, char to, char aux) {
5 // Base case
6 if (n == 1) {
7 cout << "Move disk 1 from " << from << " to " << to << endl;
8 return;
9 }
10
11 // Move n-1 disks from 'from' to 'aux' using 'to' as auxiliary
12 towerOfHanoi(n - 1, from, aux, to);
13
14 // Move the largest disk from 'from' to 'to'
15 cout << "Move disk " << n << " from " << from << " to " << to << endl;
16
17 // Move n-1 disks from 'aux' to 'to' using 'from' as auxiliary
18 towerOfHanoi(n - 1, aux, to, from);
19}
20
21int main() {
22 int n;
23 cout << "Enter number of disks: ";
24 cin >> n;
25
26 cout << "\nTower of Hanoi solution:" << endl;
27 cout << "Moving " << n << " disks from A to C using B as auxiliary\n" << endl;
28
29 towerOfHanoi(n, 'A', 'C', 'B');
30
31 // Calculate total moves
32 int totalMoves = (1 << n) - 1; // 2^n - 1
33 cout << "\nTotal moves required: " << totalMoves << endl;
34
35 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. 1

    Read n.

  2. 2

    towerOfHanoi(n, A, C, B).

  3. 3

    Move n − 1 disks A→B, move disk n A→C, move n − 1 disks B→C.

  4. 4

    Print the total, (1 << n) − 1.

Dry run: Tower of Hanoi

n = 2, A→C using B

  1. 1.hanoi(1, A, B, C): Move disk 1 from A to B
  2. 2.Move disk 2 from A to C
  3. 3.hanoi(1, B, C, A): Move disk 1 from B to C
  4. 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:

1.Move the top n − 1 disks from A to B, using C as the spare.
2.Move the largest disk from A to C.
3.Move the n − 1 disks from B to C, using A as the spare.

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:

Three rods: source, destination, auxiliary
n disks of different sizes
Move all disks from source to destination
Rules: only move one disk at a time, larger disk cannot be on smaller

Goal:

Move all disks to destination
Using minimum moves
Following the rules

Recursive Algorithm

Divide-and-Conquer Strategy:

1.Move n-1 disks from source to auxiliary
2.Move largest disk from source to destination
3.Move n-1 disks from auxiliary to destination

What happens here:

Breaks problem into smaller subproblems
Recursively solves subproblems
Combines solutions
Classic divide-and-conquer

Base Case

Single Disk:

if (n == 1) {

cout << "Move disk 1 from " << from << " to " << to << endl;

return;

}

What happens here:

Simplest case: one disk
Direct move: source to destination
Stops recursion
Base of recursive tree

Recursive Case

Three Steps:

1.towerOfHanoi(n-1, from, aux, to); // Move n-1 to auxiliary
2.Move largest disk to destination
3.towerOfHanoi(n-1, aux, to, from); // Move n-1 to destination

What happens here:

Recursively move n-1 disks
Move largest disk
Recursively move n-1 disks again
Each call reduces problem size

Minimum Moves

Formula:

Total moves = 2^n - 1

What happens here:

Exponential growth
For n=3: 2^3 - 1 = 7 moves
For n=4: 2^4 - 1 = 15 moves
For n=64: 2^64 - 1 moves (legendary!)

Time Complexity

Analysis:

Time: O(2^n) - exponential
Each disk requires recursive calls
Exponential growth with n
Efficient algorithm but exponential time

Space Complexity:

O(n) - recursion depth
Stack frames for each level
Linear space usage
Depends on recursion depth

When to Use This Algorithm

Good fits:

Learning recursion
Understanding divide-and-conquer
Educational purposes
Small number of disks

Not Practical For:

Large number of disks
Real-time applications
Performance-critical code
Production systems

Important Considerations

Recursive Structure:

Classic divide-and-conquer
Breaks problem into subproblems
Elegant solution
Demonstrates recursion power

Exponential Growth:

Moves grow exponentially
Large n becomes impractical
Legendary 64-disk problem
Demonstrates algorithm limits

Problem-Solving:

Teaches recursive thinking
Divide-and-conquer strategy
Breaking complex into simple
Foundation for algorithms

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.