Learn C · lesson 52 of 60 · about 10 minutes
Project: Towers of Hanoi
Solve the classic disc-moving puzzle with a few lines of recursion.
What you'll learn
- Break a big move into smaller moves
- Pass changing roles through parameters
- Count the moves a solution makes
Moving the backup disks
The backup disks sit in a stack on rack A, biggest at the bottom, and have to move to rack C, with rack B as a spare. Only one disk can move at a time, and a bigger disk can never go on a smaller one: it's the Towers of Hanoi. The report reads how many disks there are, prints every move as Move disk 1 from rack A to rack C, and ends with 3 disks moved in 7 moves. move_disks counts the moves through an int *, so every call adds to the same count in main.
The puzzle
There are three pegs, A, B and C, and a stack of discs on A, biggest at the bottom. Move them all to C, one disc at a time, never putting a bigger disc on a smaller one.
The trick is to think recursively. To move n discs from A to C:
1. Move the top n - 1 discs out of the way, from A to B
2. Move the biggest disc from A to C
3. Move the n - 1 discs from B onto it at C
Solving it
#include <stdio.h>
void hanoi(int n, char from, char via, char to) {
if (n == 0) return;
hanoi(n - 1, from, to, via);
printf("%c -> %c\n", from, to);
hanoi(n - 1, via, from, to);
}
int main(void) {
hanoi(2, 'A', 'B', 'C');
return 0;
}Output
A -> B
A -> C
B -> CCounting moves
Moving n discs takes the moves for n - 1 discs, plus one, plus the moves for n - 1 again. A recursive function that returns 2 * moves(n - 1) + 1 works it out, and it always comes to 2ⁿ − 1.
How many moves?
#include <stdio.h>
long moves(int n) {
if (n == 0) return 0;
return 2 * moves(n - 1) + 1;
}
int main(void) {
for (int n = 1; n <= 5; n++) printf("%d discs: %ld moves\n", n, moves(n));
return 0;
}Output
1 discs: 1 moves
2 discs: 3 moves
3 discs: 7 moves
4 discs: 15 moves
5 discs: 31 movesCounting through a pointer
move_disks counts the moves as it prints them. Every call has to add to the same count, so it takes int *moves, a pointer to the one variable in main, and adds with (*moves)++. Passing a plain int would give each call its own copy, and the count in main would stay 0.
One counter for every call
#include <stdio.h>
void count_calls(int n, int *calls) {
(*calls)++;
if (n > 0) count_calls(n - 1, calls);
}
int main(void) {
int calls = 0;
count_calls(4, &calls);
printf("%d calls\n", calls);
return 0;
}Output
5 callsTip
The pegs swap roles in each call: the peg you're moving to becomes the spare, and the spare becomes the target. Passing them as parameters handles that for you.
Now try it yourself
This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.