The Tower of Hanoi moves n disks from a source peg to a target peg using a spare peg, one disk at a time, never placing a larger disk on a smaller one. The recursive solution: move n - 1 disks to the spare peg, move the largest disk to the target, then move the n - 1 disks from the spare to the target. It takes 2^n - 1 moves.
Remember
hanoi(n, from, to, via):
if n == 0: return
hanoi(n - 1, from, via, to)
move disk n from -> to
hanoi(n - 1, via, to, from)
Reference
Cheat Sheet
Keep these facts handy while you work with Tower of Hanoi in C.
Topic
Detail
Moves
2^n - 1
Base case
n == 0
Three parts
Move n-1, move 1, move n-1
Time
O(2^n)
Code
C Examples
Compile each example with gcc file.c -std=c11 -Wall -o out. Next: Backtracking Basics.
Example 1 — Solve for three disks
Pegs A (source), C (target), B (spare).
C
#include <stdio.h>
static int moves;
static void hanoi(int n, char from, char to, char via) {
if (n == 0) return;
hanoi(n - 1, from, via, to);
printf("%d: disk %d %c->%c\n", ++moves, n, from, to);
hanoi(n - 1, via, to, from);
}
int main(void) {
hanoi(3, 'A', 'C', 'B');
printf("total moves: %d\n", moves);
return 0;
}
Output
1: disk 1 A->C
2: disk 2 A->B
3: disk 1 C->B
4: disk 3 A->C
5: disk 1 B->A
6: disk 2 B->C
7: disk 1 A->C
total moves: 7
How It Works
Moves 1 to 3 clear disks 1 and 2 onto peg B.
Move 4 puts the largest disk on peg C.
Moves 5 to 7 bring disks 1 and 2 onto peg C. The total is 2^3 - 1 = 7.
Edge Cases & Pitfalls
Check these before relying on Tower of Hanoi in real programs.
swap
Swapping pegs wrongly
The pegs rotate: the spare and target swap roles between the two recursive calls.
big
Large n
64 disks would need about 1.8 x 10^19 moves.
Remember
Key Takeaways
Move n-1, move one, move n-1.
2^n - 1 moves.
Pegs swap roles.
One line: The Tower of Hanoi moves n disks from a source peg to a target peg using a spare peg, one disk at a time, never placing a larger disk on a smaller one.
Frequently Asked Questions
2^n - 1 moves for n disks, which is the minimum.
Move the top n-1 disks out of the way, move the largest disk, then move the n-1 disks on top of it.
Continue with "C Backtracking Basics" next. Find subsets that sum to a target by trying and undoing choices. The C Recursion and Backtracking hub lists every topic in order.