Tower of Hanoi in C

What is Tower of Hanoi?

All must be well aware of the problem of Tower of Hanoi, for those who don’t know, let’s discuss it once again.

The Tower of Hanoi (also called the Tower of Brahma or Lucas’ Tower, and sometimes pluralized) is a mathematical game or puzzle.

t tower of hanoi

 

It consists of three rods, and a number of disks of different sizes which can slide onto any rod. The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the smallest at the top, thus making a conical shape.

The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules:

  • Only one disk can be moved at a time.
  • Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack.
  • No disk may be placed on top of a smaller disk.

Animated Solution:

 

tower of hanoi solution

 

Program to solver Tower of Hanoi in C (using recursion):

#include <stdio.h>
 
void towers(int, char, char, char);
 
int main()
{
 int num;
 
 printf("Enter the number of disks : ");
 scanf("%d", &num);
 printf("The sequence of moves involved in the Tower of Hanoi are :\n");
 towers(num, 'A', 'C', 'B');
 return 0;
}
void towers(int num, char frompeg, char topeg, char auxpeg)
{
 if (num == 1)
 {
 printf("\n Move disk 1 from peg %c to peg %c", frompeg, topeg);
 return;
 }
 towers(num - 1, frompeg, auxpeg, topeg);
 printf("\n Move disk %d from peg %c to peg %c", num, frompeg, topeg);
 towers(num - 1, auxpeg, topeg, frompeg);
}

SAMPLE OUTPUT:

cc towerofhanoi.c
$ a.out
Enter the number of disks : 3
The sequence of moves involved in the Tower of Hanoi are :
 
Move disk 1 from peg A to peg C
Move disk 2 from peg A to peg B
Move disk 1 from peg C to peg B
Move disk 3 from peg A to peg C
Move disk 1 from peg B to peg A
Move disk 2 from peg B to peg C
Move disk 1 from peg A to peg C

1 thought on “Tower of Hanoi in C”

Leave a Comment