Recursive C program for Towers of Hanoi

Towers of Hanoi problem consists of 3 pegs A, B and C. Let n denote number of disks in peg A. The objective is to transfer these disks from A to C using B as auxiliary so that at a time only one disk is transferred and a larger one cannot reside on a smaller one.

The following recursive algorithm could be generated to solve the Towers of Hanoi –

1) if ( n == 1 )

move the only disk from A to C

2) move the top(n-1) disks from peg A to B using C as auxiliary

3) move the remaining disk from peg A to C

4) move the (n-1) disks from B to C using A as auxiliary

The above algorithm could be easily converted into a recursive C program as follows –

/* Towers of Hanoi */

main(){
         void Haoi (int, char, char, char);
         printf("\nEnter number of Disks>");
         scanf("%d", &n);
         Hanoi(n,'A','C','B');
}/* end main */

void Hanoi (int n, char frompeg, char topeg, char auxpeg){
         if(n==1) /* move the only disk from A to C */
              printf("\nMove disk1 from %s to %s", frompeg, topeg);
         Hanoi(n-1, frompeg, auxpeg, topeg);
         printf("\nMove disk%d from %s to %s", n, frompeg, topeg);
         Hanoi(n-1, auxpeg, topeg, frompeg);
         printf("\nMove disk%d from %s to %s", n, frompeg, topeg);
         return;
} /* end Hanoi */

Add a Comment

Your email address will not be published. Required fields are marked *