Tower of Hanoi - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Random Posts


In this puzzle, three poles are given and in one pole a set of disks with different size are given. These disks are arranged in such a way that a disk on top of another is always smaller than the previous one.

Objective of this puzzle is to move all the disks to another pole with two important constraints. The constraints are:

  1. only one disk can move at a time and
  2. a larger disk cannot be placed on top of smaller one.
Implementation of the Tower of Hanoi problem
#include <stdio.h> void towers(int num, char from, char to, char aux); int main() { int num; printf("Enter the number of disks : "); scanf("%d", &num); printf("The moves involved in the ToH are :\n"); towers(num, 'A', 'C', 'B'); return 0; } void towers(int num, char from, char to, char aux) { if (num == 1) { printf("\n Move disk 1 from %c to %c", from, to); return; } towers(num - 1, from, aux, to); printf("\n Move disk %d from %c to %c", num, from, to); towers(num - 1, aux, to, from); }

Happy Exploring!

No comments:

Post a Comment