C Program For Towers Of Hanoi

Ram Pothuraju
#include<stdio.h>
#include<conio.h>

#include<math.h>
void tower_of_hanoi(int,char,char,char);

void main()
{
 int disk,move;
 clrscr();
 printf("\n Enter number of disks:");
 scanf("%d",&disk);
 move=pow(2,disk)-1;
 printf("\n No. of moves required is:%d",move);
 printf("\n A-->Source peg\n B-->Destination peg \n C-->Auxiliary peg");
 tower_of_hanoi(disk,'A','B','C');

getch();
}

void tower_of_hanoi(int disk,char from,char to,char aux)
{
 if(disk==1)
 {
  printf("\n move disk %d from %c to %c",disk,from,to);
 }
 else
 {
  tower_of_hanoi(disk-1,from,aux,to);
  printf("\n move disk %d from %c to %c",disk,from,to);
  tower_of_hanoi(disk-1,aux,to,from);
 }
}
</math.h></conio.h></stdio.h>


OUTPUT


Enter number of disks:4

No. of moves required is:15
A-->Source peg
B-->Destination peg
C-->Auxiliary peg
move disk 1 from A to C
move disk 2 from A to B
move disk 1 from C to B
move disk 3 from A to C
move disk 1 from B to A
move disk 2 from B to C
move disk 1 from A to C
move disk 4 from A to B
move disk 1 from C to B
move disk 2 from C to A
move disk 1 from B to A
move disk 3 from C to B
move disk 1 from A to C
move disk 2 from A to B
move disk 1 from C to B

Post a Comment

0Comments

Post a Comment (0)