Program for tower of hanoi in C.

#include<stdio.h>
void hanoi(int p,char q,char r,char s);
main()
{
int n;
printf("enter the number of rings\n");
scanf("%d",&n);
/* A is the source peg*/
/* B is the auxillary peg */
/* C is the target peg */
hanoi(n,'A','C','B');
}
void hanoi(int n,char P,char R,char Q)
{
/* P is the source peg*/
/* Q is the auxillary peg */
/* R is the target peg */
if(n==1){
printf("\n%s%c%s%c","move ring 1 from peg ",P," to peg ",R);
return;
}
hanoi(n-1,P,Q,R);
printf("\n%s%d%s%c%s%c","move ring ",n," from peg ",P ," to peg ",R);
hanoi(n-1,Q,R,P);
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s