Wednesday 12 September 2012

To solve the towers of Hanoi problem by using the recursive function


Description:
Towers of Hanoi problem means we have three towers
Here source ,intermediate and destination are the three towers. We have to transfer all the disks from source to destination towers. Here the restriction is not to place a big disk on smaller one . for this we use intermediate tower. Finally the arrangements in the destination tower must be as same as the disks in the source tower at first.
Algorithm: main program
Step 1: start
Step 2: initialize the source=a, intermediate=c, destination = d
Step 3: read n
Step 4: call the sub program Hanoi recursion (n value,a ,b, c)
Step 5: stop
           Sub program:
Step 1: if n== 1 call the sub program Hanoi recursion (num-1, a, c, b)
Step 2: print the output from a to b
Step 3: call the sub program Hanoi recursion(num-1, b, c, a)
Step 4: return to main program

 
Program:
#include<stdio.h>
#include<conio.h>
void Hanoirecursion(int num,char ndl1,char ndl2,char ndl3)
{
  if(num==1)
   {
             printf("Move top disk from needle %c to needle %c",ndl1,ndl2);
              return;
   }
            Hanoirecursion(num-1,ndl1,ndl3,ndl2);
             printf("Move top dis from needle %c to needlle %c",ndl1,ndl2);
            Hanoirecursion(num-1,ndl3,ndl2,ndl1);
}

void main()
{
             int no;
             clrscr();
             printf("Enter the no. of disk to be transferred:");
             scanf("%d",&no);
             if(no<1)
             printf("\n There's nothing to move");
            else
            printf("\n recursive");
            Hanoirecursion(no,'A','B','C');
            getch();
}
Outputs:
1. Enter the no. of disk to be transferred :3
     Move top disk from needle a to needle b
    Move top disk from needle a to needle c
     Move top disk from needle b to needle c
     Move top disk from needle a to needle b
    Move top disk from needle c to needle a
    Move top disk from needle c to needle b
    Move top disk from needle a to needle b
Conclusion:
The program is error free
VIVA QUESATIONS:
1)      What is purpose of towers of Hanoi ?
Ans: We have to transfer all the disks from source to destination towers. Here the restriction is not to place a big disk on smaller one . for this we use intermediate tower. Finally the arrangements in the destination tower must be as same as the disks in the source tower at first.

No comments:

Post a Comment