Tower of Hanoi in C.

 

01  #include<stdio.h>
02
03 void hanoi(int n, char initial,char final, char temp)
04 {
05 if(n==1)
06 {
07 printf("move disk 1 from peg %c to %c n",initial,final);
08 return;
09 }
10
11 hanoi(n-1,initial,temp,final);
12 printf("move disk %d from peg %c to %c n",n,initial,final);
13 hanoi(n-1,temp,final,initial);
14 }
15
16 int main()
17 {
18 int n;
19 printf("Enter no. of disks to be moved : ");
20 scanf("%d",&n);
21 hanoi(n,'A','C','B');
22
23 return 0;
24 }
 
 OUTPUT :

Enter no. of disks to be moved : 3

move disk 1 from peg A to C
move disk 2 from peg A to B
move disk 1 from peg C to B
move disk 3 from peg A to C
move disk 1 from peg B to A
move disk 2 from peg B to C
move disk 1 from peg A to C

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.