Right Click to Search

Saturday, July 24, 2024

Recursive Program for Tower of Hanoi


#include<stdio.h>
#include<conio.h>
void TOH(int n,char x,char y,char z);
void main()
{
 int n;
 printf("\n Enter number of plates:");
 scanf("%d",&n);
 TOH(n-1,'A','B','C');
 getch();
}
void TOH(int n,char x,char y,char z)
{
 if(n>0)
 {
  TOH(n-1,x,z,y);
  printf("\n%c -> %c",x,y);
  TOH(n-1,z,y,x);
 }
}


Tags / Keywords : |

Stumble
Delicious
Technorati
Twitter
Facebook

1 Comment:

andy said...

I guess there are few mistakes in the code:

The output for 3 plates should be:

A -> C
A -> B
C -> B
A -> C
B -> A
B -> C
A -> C

==============
The correct code is:

#include
#include
void TOH(int n,char x,char y,char z);
void main()
{
int n;
printf("\n Enter number of plates:");
scanf("%d",&n);
TOH(n,'A','B','C'); //instead of n-1
getch();
}
void TOH(int n,char x,char y,char z)
{
if(n>0)
{
TOH(n-1,x,z,y);
printf("\n%c -> %c",x,z); //instead of x,y
TOH(n-1,y,x,z); //instead of z,y,x
}
}

Post a Comment

Your Feedback :This is Growing Site and Your Feedback is important for Us to improve the Site performance & Quality of Content.Feel Free to contact and Please Provide Name & Contact Email

 

Learn C Programming Copyright © 2010 LKart Theme is Designed by Lasantha, Free Blogger Templates