Tower of Hanoi Problem implementation in C

              Tower of Hanoi is a classical problem in operating system. It has rods and disks. To arrange it in a particular order, this program is used.

Steps to follow:

  •               Create a function towerofHanoi()with four parameters. No- number of disks, source and auxiliary and destination.
  • First, the control moves no-1 disks to the auxiliary rod.
  • Next, it moves the largest disk to the destination.
  • At last, it moves the no-1 disks from auxiliary to destination.

C Program:

#include <stdio.h>

 // function towerofHanoi

void towerofHanoi(int no, char src, char auxi, char dest) {

    if (no == 1) {

        printf("Move disk 1 from %c to %c\n", src, dest);

        return;

    }

     // As a beginning,Move n-1 disks from source to auxiliary

    towerofHanoi(no - 1, src, dest, auxi);

     // Next, Move the nth disk from source to destination

    printf("Move disk %d from %c to %c\n", no, src, dest);

     // Finally ,Move n-1 disks from auxiliary to destination

    towerofHanoi(no - 1, auxi, src, dest);

}

 int main() {

    int nDisks;

     printf("Enter the number of disks: ");

    scanf("%d", &nDisks);

     printf("\nThe Steps to solve Tower of Hanoi with %d disks:\n", nDisks);

    towerofHanoi(nDisks, 'X', 'Y', 'Z');

    // where X = source, Y = auxiliary, Z = destination

     return 0;

}

Output:

Enter the number of disks: 4

The Steps to solve Tower of Hanoi with 4 disks:

Move disk 1 from X to Y

Move disk 2 from X to Z

Move disk 1 from Y to Z

Move disk 3 from X to Y

Move disk 1 from Z to X

Move disk 2 from Z to Y

Move disk 1 from X to Y

Move disk 4 from X to Z

Move disk 1 from Y to Z

Move disk 2 from Y to X

Move disk 1 from Z to X

Move disk 3 from Y to Z

Move disk 1 from X to Y

Move disk 2 from X to Z

Move disk 1 from Y to Z

That’s it. The C program to implement tower of Hanoi is done. Hope, this code is useful to you. Keep Coding!!!!

Comments

Popular posts from this blog

How to create a XML DTD for displaying student details

How to write your first XML program?

Java NIO examples to illustrate channels and buffers.