🗼
004. The Tower of Hanoi
TL;DR
- The Puzzle: Three rods, stack of disks, one rule—never put a big disk on a small one.
- The Concept: Recursion. A function that calls itself until the problem is solved.
- The Feeling: Pure confusion. Then it clicks. Then confusion again.
Staring at Disks
I am currently staring at the Tower of Hanoi. In theory, it's a simple puzzle. In C, it is a nightmare. This is my first real introduction to recursion—a function that calls itself.
It feels unnatural. My brain wants to solve things step-by-step, like a circuit. But recursion requires you to trust that the function will handle the smaller versions of the problem. You don't trace every step—you define the logic and let it unfold. If you get one step wrong, the whole thing collapses into a stack overflow.

The Code
The idea: move n disks from rod A to rod C, using rod B as a helper. The trick is you break it into three steps:
- 1. Move the top
n-1disks out of the way (to the helper rod). - 2. Move the biggest disk to the destination.
- 3. Move the
n-1disks from the helper rod to the destination.
And steps 1 and 3? They're the same problem, just smaller. That's recursion.
#include <stdio.h>
void solveHanoi(int n, char source, char dest, char aux) {
if (n == 1) {
printf("Move disk 1 from %c to %c\n", source, dest);
return;
}
solveHanoi(n - 1, source, aux, dest);
printf("Move disk %d from %c to %c\n", n, source, dest);
solveHanoi(n - 1, aux, dest, source);
}
int main() {
int disks = 4;
solveHanoi(disks, 'A', 'C', 'B');
return 0;
}The Analogy
There are moments where I feel like I'm finished. Between pointers and this logical loop, I feel lost. But then it clicked—programming is the Tower of Hanoi. You can't just jump to the solution. You have to move smaller pieces first, build understanding one layer at a time, and trust that each step gets you closer.
I haven't mastered it yet. But the disks are moving.
Keep moving.
<- Back to blog
All rights not reserved. Do you want a website like this? Just copy it 👍🏾