C Tower of Hanoi

Intermediate
6 min read
Updated: Nov 2026
1 example

Moving Disks Between Pegs

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)

Cheat Sheet

Keep these facts handy while you work with Tower of Hanoi in C.

TopicDetail
Moves2^n - 1
Base casen == 0
Three partsMove n-1, move 1, move n-1
TimeO(2^n)

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;
}

How It Works

  1. Moves 1 to 3 clear disks 1 and 2 onto peg B.
  2. Move 4 puts the largest disk on peg C.
  3. 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.

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.

Next: Backtracking Basics

Find subsets that sum to a target by trying and undoing choices.

Continue →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

11 people found this page helpful