Sunday, 24 December 2017

Write a program in C to implement Tower of Hanoi algorithm.

Working of the tower of Hanoi in the below picture:



Implementation of the above problem:

#include <stdio.h>
void towers(int,char,char,char);
void towers(int n,char fromplace,char toplace,char auxplace)
/* If only 1 disk, make the move and return */
if(n==1)
printf("\nMove disk 1 from place %c to place %c",fromplace,toplace);
return;
}

/* Move top n-1 disks from A to B, using C as auxiliary */
towers(n-1,fromplace,auxplace,toplace);

/* Move remaining disks from A to C */
printf("\nMove disk %d from place %c to place %c",n,fromplace,toplace);

/* Move n-1 disks from B to C using A as auxiliary */
towers(n-1,auxplace,toplace,fromplace);}

main()
{
int n;
printf("Enter the number of disks : ");
scanf("%d",&n);
printf("The Tower of Hanoi involves the moves :\n\n");
towers(n,'A','C','B');
return 0;
}


Thanks
Mukesh Rajput

No comments:

Post a Comment

Thanks
Mukesh Rajput