C code for Towers of Hanoi

The famous Towers of Hanoi problem has an elegant solution through recursion. In the problem, three pegs, A, B and C exist. ‘n’ disks of differing diameters are placed on peg A so that the larger disk is always below a smaller disk. The objective is to move all the disks to peg C using peg B as auxiliary. Only the top disk on any peg may be moved to any other peg, and the larger disk may never rest on a smaller one.

Programming Geeks : Towers of Hanoi

The recursive solution involves the following steps :

1. if n==1, move the single disk from A to C and stop.

2. Move the top n-1 disks from A to B, using C as auxiliary.

3. Move the remaining disk from A to C.

4. Move the n-1 disks from B to C, using A as auxiliary.

The exe file for the C code of this problem can be downloaded from here : TOWERS.

The C code is presented below :


#include "stdio.h"

void towers(int,char,char,char);

void towers(int n,char frompeg,char topeg,char auxpeg)
	{ /* If only 1 disk, make the move and return */
	  if(n==1)
	    { printf("\nMove disk 1 from peg %c to peg %c",frompeg,topeg);
	      return;
	    }
	  /* Move top n-1 disks from A to B, using C as auxiliary */
	  towers(n-1,frompeg,auxpeg,topeg);
	  /* Move remaining disks from A to C */
	  printf("\nMove disk %d from peg %c to peg %c",n,frompeg,topeg);
	  /* Move n-1 disks from B to C using A as auxiliary */
	  towers(n-1,auxpeg,topeg,frompeg);
	}
main()
	{ int n;
	  printf("Enter the number of disks : ");
	  scanf("%d",&n);
	  printf("The Tower of Hanoi involves the moves :\n\n");
	  towers(n,'A','C','B');
	  return 0;
	}


Related Posts

Share

Filed Under: AlgorithmsCCodesFeatured

Tags:

About the Author: Software Engineer - Advanced Search & Recommendation at Rovi

RSSComments (9)

Leave a Reply | Trackback URL

  1. sheetal says:

    C program to get the value of sin (x) using a library function , when x is given in degrees

  2. sheetal says:

    Thanks,

  3. debashis says:

    Thanks, I was just searching for the solution for my assignment and i got that and later i ‘ll just make me understand that what is the code. Thanks a lot

  4. Amit Kulkarni says:

    Thanx………… but give some explanation about that recursion code plz

  5. sandhya says:

    thanx…4r d prgrm…

  6. Hemant says:

    Thanx For the Source Code… :) :)

  7. Robo says:

    There is typo in point 4 – it should be from B to C using A instead from B to C, using C as auxiliary. Other than that it’s good.

Leave a Reply

*

AWSOM Powered