Tower of Hanoi Program in C

Tower of Hanoi:

Tower of Hanoi is a famous recursive problem which is based on 3 pegs and a set of discs of different sizes. It consists of some wooden disks and three poles attached to a baseboard. The disks each have different diameters and a hole in the middle large enough for the poles to pass through. The object of the puzzle is to move all the disks over to the right pole, one at a time, so that they end up in the original order on that pole. The middle pole may be used as a temporary resting place for disks, but at no time is a larger disk to be on top of a smaller one. In the C program, we try to solve the Tower of Hanoi.

C Program for Tower of Hanoi:

void toh(int, char, char, char);
void main()
   int n;
   printf("Enter the number of disk: ");
   scanf("%d", &n);
   printf("Here is sequence of moves of tower of hanoi:\n");
   toh(n, '1', '3', '2');
void toh(int no, char source, char destination, char spare)
   if (no == 1)
         printf("\n move disk 1 from source %c to destination %c", source, destination);
  toh(no - 1, source, spare, destination);
  printf("\n move disk %d from source %c to destination %c", no, source, destination);
  toh(no - 1, spare, destination, source);


Tower of Hanoi Program in C

Leave a Reply

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