🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Tower of Hanoi in C
Solve the classic puzzle with recursion, prove why it needs 2n − 1 moves, and learn the thinking style that powers embedded C programming.
The Tower of Hanoi in C is the best first puzzle for anyone learning recursion. In this lecture of our free C programming course you will turn a three-line idea into a working program, trace it by hand, and see exactly how many moves it makes. If you are following this free C tutorial to prepare for C programming for embedded systems, the habits you build here — define a base case, shrink the problem, trust the function call — will show up again in parsers, state machines and tree walkers.
What You Will Learn
- The rules of the Tower of Hanoi puzzle and the vocabulary used to describe it.
- How to break an n-disc problem into two (n−1)-disc problems plus one move.
- Two valid base cases (one disc, or zero discs) and why both work.
- How to derive and verify the 2n − 1 move count.
- How to write, compile and run an original Tower of Hanoi program in C.
- How to trace the program step by step for three discs.
- Common mistakes, input validation and performance limits.
Prerequisites
You should be comfortable with function definitions, parameters and return types, and with printf and scanf. If the idea of a function calling itself is new, read the earlier lectures on recursion (factorial, power and Fibonacci) in this chapter first. A GCC or Clang compiler on Linux, macOS or WSL is all you need; the same code builds with any C99 toolchain, including the ones used for microcontrollers.
The Tower of Hanoi in C: Puzzle and Rules
Imagine three pegs and a stack of discs of different sizes threaded on the first peg, largest at the bottom. The goal is to move the whole stack to another peg. Only three rules apply:
- Move exactly one disc at a time.
- Only the top disc of a peg can be lifted.
- A larger disc must never sit on top of a smaller one.
In code we name the pegs by their role. In this lecture the starting peg is A, the helper peg is B and the destination is C. Important detail: the roles change as the recursion goes deeper. A peg that was the helper in one call becomes the source or destination in the next, which is why the function receives the peg names as parameters instead of hard-coding them.
Start state for 3 discs
Thinking Recursively About the Tower of Hanoi in C
Do not try to plan every move. Instead ask one question: what must be true just before the largest disc moves? The largest disc can travel only if every smaller disc is out of its way, and they cannot be on the destination (the big disc is going there). So all n−1 smaller discs must be parked on the helper peg. That observation gives a complete strategy in three phases.
The three-phase recursive strategy
Phase 1 – clear the way
Move the top n−1 discs from the source to the helper peg. The destination is used as the temporary peg.
hanoi(n−1, from, to, via)Phase 2 – the big move
Move disc number n, the largest of the group, directly from the source to the destination. This is the only line that prints a move.
print one movePhase 3 – rebuild on top
Move the n−1 discs from the helper peg to the destination. The source peg is now the temporary peg.
hanoi(n−1, via, from, to)Notice that phases 1 and 3 are the same puzzle with fewer discs and with the pegs playing different roles. That is the textbook shape of recursion: a smaller copy of the same problem, repeated until it becomes trivial.
Writing the rule as a recurrence
Let H(n, from, via, to) mean “move n discs from from to to using via”. Then:
| Condition | What H does |
|---|---|
| n = 1 (book-style base case) | Move the single disc from from to to |
| n > 1 | H(n−1, from, to, via), move disc n, then H(n−1, via, from, to) |
| n = 0 (our base case) | Do nothing and return |
Many textbooks stop at one disc. We prefer stopping at zero discs because it removes a special case: the general rule already produces the right single move when n is 1, because both recursive calls return immediately. Fewer branches means fewer places for bugs, which matters just as much in firmware as on a desktop.
How Many Moves Does the Puzzle Need?
Let T(n) be the number of moves. Phase 1 costs T(n−1), phase 2 costs one move, and phase 3 costs T(n−1) again, so T(n) = 2·T(n−1) + 1 with T(0) = 0. Unrolling the pattern gives T(1) = 1, T(2) = 3, T(3) = 7, T(4) = 15 and in general T(n) = 2n − 1. The growth is exponential, which has practical consequences you will see in the performance section.
| Discs (n) | Moves 2n − 1 | Practical meaning |
|---|---|---|
| 3 | 7 | Fits on one screen |
| 5 | 31 | A few seconds by hand |
| 10 | 1,023 | Instant on a computer |
| 20 | 1,048,575 | Printing becomes the bottleneck |
| 30 | 1,073,741,823 | Over a billion moves; avoid printing |
Tower of Hanoi in C: Complete Program
Here is an original implementation. It uses a file-level counter to number the steps, validates the user input, and treats zero discs as the base case.
#include <stdio.h>
static unsigned long step_no;
static void hanoi(int discs, char from, char via, char to)
{
if (discs == 0) {
return;
}
hanoi(discs - 1, from, to, via);
step_no++;
printf("Step %2lu : move disc %d from %c to %c\n", step_no, discs, from, to);
hanoi(discs - 1, via, from, to);
}
int main(void)
{
int discs;
printf("How many discs? ");
if (scanf("%d", &discs) != 1 || discs < 0 || discs > 20) {
printf("Enter a number between 0 and 20\n");
return 1;
}
hanoi(discs, 'A', 'B', 'C');
printf("Total moves = %lu\n", step_no);
return 0;
}
Line-by-line explanation
static unsigned long step_no;– a file-scope variable, zero-initialised by the C runtime. Because it isstatic, other source files cannot see it. Being unsigned long, it comfortably counts 220 − 1 moves.if (discs == 0) return;– the base case. Without it the function would call itself forever with negative disc counts.- The first recursive call uses
(from, to, via): the destination and helper swap roles so the small tower lands on the helper peg. - The
printfsits between the two recursive calls. That position is what makes the output come out in the correct order; move it before or after both calls and the move list is wrong. - The second recursive call uses
(via, from, to): now the helper is the source of the small tower. - In
main, the checkscanf(...) != 1rejects non-numeric input, and the range check protects against a request for billions of lines.
Build and run
$ gcc -Wall -Wextra -std=c99 -o hanoi hanoi.c
$ ./hanoi
How many discs? 3
Step 1 : move disc 1 from A to C
Step 2 : move disc 2 from A to B
Step 3 : move disc 1 from C to B
Step 4 : move disc 3 from A to C
Step 5 : move disc 1 from B to A
Step 6 : move disc 2 from B to C
Step 7 : move disc 1 from A to C
Total moves = 7
Seven moves, exactly 23 − 1. Replay the list on paper with three coins of different sizes and you will see every rule obeyed.
Tracing the Tower of Hanoi in C for Three Discs
The table below lists each printed step together with the recursive call that produced it. Each call is written as hanoi(discs, from, via, to), exactly as in the program.
| Step | Printed by call | Move | Why this move happens |
|---|---|---|---|
| 1 | hanoi(1, A, B, C) | disc 1: A to C | Smallest disc starts clearing the way for disc 3 |
| 2 | hanoi(2, A, C, B) | disc 2: A to B | Disc 2 goes to the helper peg |
| 3 | hanoi(1, C, A, B) | disc 1: C to B | Disc 1 rebuilds on top of disc 2 |
| 4 | hanoi(3, A, B, C) | disc 3: A to C | The largest disc makes its single move |
| 5 | hanoi(1, B, C, A) | disc 1: B to A | Clearing the way for disc 2 |
| 6 | hanoi(2, B, A, C) | disc 2: B to C | Disc 2 lands on disc 3 |
| 7 | hanoi(1, A, B, C) | disc 1: A to C | Final move completes the tower |
Pattern to remember
The smallest disc moves on every odd-numbered step and always cycles in the same direction. For an odd disc count it hops A, C, B, A, C and so on. This observation leads to a non-recursive solution that you can explore as an exercise.
Real-World Uses of the Tower of Hanoi in C
- Teaching and interviews: the puzzle is a standard way to check whether a candidate really understands recursion rather than memorising factorial.
- Backup rotation: the Tower of Hanoi backup scheme reuses media on a schedule that follows the same power-of-two pattern.
- Divide and conquer: splitting a task into smaller identical tasks plus a combining step appears in sorting, tree traversal and protocol parsing.
- Stack awareness: because the maximum call depth is n + 1, the program is a clean laboratory for studying stack usage, a daily concern in embedded C programming.
Common Mistakes and Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| Moves look wrong but count is right | Swapped helper and destination in one recursive call | First call: (from, to, via). Second call: (via, from, to) |
| Program crashes with segmentation fault | Missing base case, so recursion never stops | Return early when discs == 0 |
| Output order is scrambled | printf placed before or after both recursive calls | Print only between the two calls |
| Counter shows a negative or odd number | Used int for a large count | Use unsigned long for the move counter |
| Terminal floods for large n | No input limit | Reject values above a sensible bound |
Warning: never pass user input straight into a recursive function without a range check. An unchecked depth can exhaust the stack on a small microcontroller long before it becomes a problem on a PC.
Best Practices, Performance and Security
- Name parameters by role (
from,via,to) so the swapped calls read naturally. - Keep the printing separate from the logic if you reuse the solver; pass a callback or write into a buffer so the algorithm can be tested without a terminal.
- Performance: the work is exponential. Computing 30 discs without printing still needs over a billion calls, and printing a million lines is usually slower than the recursion itself.
- Memory: stack depth is only n + 1 frames, so the memory cost is linear even though the time cost is exponential.
- Security and safety: validate input, bound the recursion depth and use unsigned counters to avoid signed-overflow undefined behaviour.
Summary and Key Takeaways
- Moving n discs equals moving n−1 discs, moving one disc, then moving n−1 discs again.
- The peg roles swap between calls; passing them as parameters makes that automatic.
- A zero-disc base case is simpler than a one-disc base case.
- The minimum number of moves is 2n − 1.
- The print statement belongs between the two recursive calls.
Conclusion
You have now written the Tower of Hanoi in C from first principles, verified its output against the mathematics and examined the mistakes that trip up most beginners. The same discipline — a clear base case, a strictly smaller problem and a single point of work — carries straight into C programming for embedded systems, where you will walk linked lists, parse nested messages and traverse device trees. In the next lecture of this free embedded C course we open the hood and watch the call stack grow and shrink while this program runs.
Frequently Asked Questions
What is the minimum number of moves for the Tower of Hanoi?
For n discs the minimum is 2n − 1. Three discs need 7 moves, four need 15, and ten need 1,023.
Why is recursion a natural fit for the Tower of Hanoi in C?
Because the problem contains smaller copies of itself: moving n discs requires moving n−1 discs twice. A recursive function states that relationship directly in a few lines.
Should the base case be zero discs or one disc?
Both are correct. One disc matches many textbooks, while zero discs removes a special case and keeps the function shorter.
Can the Tower of Hanoi be solved without recursion?
Yes. An iterative version moves the smallest disc in a fixed cyclic direction on odd steps and makes the only legal move among the other two pegs on even steps. It needs an explicit loop but no call stack.
How deep does the call stack go?
The maximum depth is n + 1 frames including the base-case call, so even 20 discs need only 21 active frames.
Is this lecture part of a free C programming course?
Yes. It belongs to the Functions chapter of the EmbeddedPathashala free C programming course, written for students who want to move on to embedded C programming.

2 Comments