Learn Programming C | C++ | Java | Android | Tips and Tricks

C Program to print Tower of Hanoi using recursion !!

Article Viewed : 923 times. 2 Comments
#include<stdio.h>
#include<conio.h>
void TOH(int n,char x,char y,char z);
void main()
{
 int n;
 printf("\nEnter 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);
 }
}

Following Image will explain you more about tower of hanoi :

About The Author

My name is Pritesh Taral. I am working in well known MNC. as Java Developer. I am part time blogger loves writing articles on C/C++. I am active on facebook using community fan page .One can Visit me @ Facebook Facebook Fan Page

  • andy

    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
    }
    }

  • http://alexhashemian.com/index.php/2011/11/a-consumers-manual-to-led-flashlights/ Emory Ottinger

    In this grand pattern of things you receive a B- for effort. Exactly where you actually lost everybody was first in the facts. As they say, the devil is in the details… And it couldn’t be much more correct right here. Having said that, let me inform you what did deliver the results. Your authoring is actually incredibly convincing and this is most likely the reason why I am making an effort to opine. I do not really make it a regular habit of doing that. Next, although I can easily notice a jumps in logic you make, I am definitely not certain of how you appear to unite your points which in turn produce the conclusion. For now I shall yield to your position but hope in the future you link the facts much better.