Subscribe

RSS Feed (xml)

Wednesday, February 11, 2009

Write a C program to solve the Towers of Hanoi problem using Recursive function.

#include(stdio.h) // place this '<' & '>' instead of '(' & ')' before stdio.h
#include(conio.h)
#include(math.h)
void hanoi(int x, char from, char to, char aux)
{
if(x==1)
printf("Move Disk From %c to %c\n",from,to);
else
{
hanoi(x-1,from,aux,to);
printf("Move Disk From %c to %c\n",from,to);
hanoi(x-1,aux,to,from);
}
}
void main( )
{
int disk;
int moves;
clrscr();
printf("Enter the number of disks you want to play with:");
scanf("%d",&disk);
moves=pow(2,disk)-1;
printf("\nThe No of moves required is=%d \n",moves);
hanoi(disk,'A','C','B');
getch( );
}

Output:-
Enter the number of disks you want to play with: 3

The No of moves required is=7
Move Disk from A to C
Move Disk from A to B
Move Disk from C to B
Move Disk from A to C
Move Disk from B to A
Move Disk from B to C
Move Disk from A to C

Note:- If u have any doubt regarding this program or logic, please feel free to contact me.

8 comments:

  1. Hi Mr.Shriram,i have query.i just want to print
    abcdefghgfedcba
    abcdefg gfedcba
    abcdef fedcba
    abcde edcba
    abcd dcba
    abc cba
    ab ba
    a a
    plz,can u send me this one upto 2morow ? this is for exam ?

    ReplyDelete
  2. abcdefghgfedcba
    abcdefg gfedcba
    abcdef fedcba
    abcde edcba
    abcd dcba
    abc cba
    ab ba
    a a

    ReplyDelete
  3. hi this is sohini.i have a doubt.in th tower of hanoi progam,there is 'moves=pow(2,disk)-1'.but in the output we find that after taking 3 disks,we have 7 moves.can u pls explain me how can we get 7 moves? as per my calculation,according to the code it will be 'moves=3^2-1=8'.


    reply

    ReplyDelete
  4. Hello,
    This is Sangeetha. I don't know if I can actually ask but most have asked you how to write a program.
    I want to print Pyramid Of Numbers like-
    12
    5 7
    2 3 4

    The last row is given by the user and the sum of first two, gives first element of second row. The sum of second two numbers gives the second element of second row. Like that.
    Can you explain me how to do that? Thanks in advance.

    ReplyDelete
  5. I'm not able to understand what is the tower of hanoi
    What am I supposed to do in this program

    ReplyDelete
  6. explain this program in step by step process...

    ReplyDelete
  7. these are really helpful for my coming examinations.. thank u Mr.Shri Ram.

    ReplyDelete