C programme to automate the tower of hanoi problem

 

Hello guys ,Once again welcome to the decoderzz blog today we will be discussing about the tower of hanoi problem in C 

But first we must understand what is this tower of hanoi.........

The Tower of Hanoi is a mathematical game or puzzle consisting of three rods and a number of disks of various diameters, which can slide onto any rod. The puzzle begins with the disks stacked on one rod in order of decreasing size, the smallest at the top, thus approximating a conical shape.

Let rod 1 = 'A', rod 2 = 'B', rod 3 = 'C'.

An example with 2 disks :

Step 1 : Shift first disk from 'A' to 'B'.

Step 2 : Shift second disk from 'A' to 'C'.

Step 3 : Shift first disk from 'B' to 'C'.


An example with 3 disks :

Step 1 : Shift first disk from 'A' to 'C'.
Step 2 : Shift second disk from 'A' to 'B'.
Step 3 : Shift first disk from 'C' to 'B'.

Step 4 : Shift third disk from 'A' to 'C'.

Step 5 : Shift first disk from 'B' to 'A'.
Step 6 : Shift second disk from 'B' to 'C'.
Step 7 : Shift first disk from 'A' to 'C'.
(Notice the gaps)
Step 2 : Shift second disk from 'A' to 'C'.

Step 3 : Shift first disk from 'B' to 'C'.
The pattern here is :
- Shift 'n-1' disks from 'A' to 'B', using C.
- Shift last disk from 'A' to 'C'.
- Shift 'n-1' disks from 'B' to 'C', using A.
#include<stdio.h>
void towerofHanoi(int n,char from_rod,char to_rod,char aux_rod)
{
  if(n==0)
  {
    return;
  }
  towerofHanoi(n-1,from_rod,to_rod,aux_rod);
  printf("Move the rod %d from %c to %c\n",n,from_rod,to_rod);
  towerofHanoi(n-1,aux_rod,to_rod,from_rod);
}
int main()
{
  int n;
  printf("Enter the value of n\n");
  scanf("%d",&n);
  towerofHanoi(n,'A','C','B');
}

Comments

Popular Posts