How to implement the Tower of Hanoi in C language?

In C language, recursion can be used to solve the Tower of Hanoi problem. Here is an example code for implementation.

#include <stdio.h>

void hanoi(int n, char from, char to, char aux) {
    if (n == 1) {
        printf("Move disk 1 from %c to %c\n", from, to);
        return;
    }
    hanoi(n - 1, from, aux, to);
    printf("Move disk %d from %c to %c\n", n, from, to);
    hanoi(n - 1, aux, to, from);
}

int main() {
    int n;
    printf("Enter the number of disks: ");
    scanf("%d", &n);
    hanoi(n, 'A', 'C', 'B');
    return 0;
}

The program utilizes a recursive function called hanoi to implement the Tower of Hanoi. This function takes four parameters: n for the number of disks to move, from for the starting pole, to for the target pole, and aux for the auxiliary pole.

The base case of recursion is when n equals to 1, simply move the plate from the starting pole to the target pole. Otherwise, move n-1 plates from the starting pole to the auxiliary pole first, then move the last plate from the starting pole to the target pole, and finally move n-1 plates from the auxiliary pole to the target pole.

In the main function, the user inputs the number of disks to be moved, and then calls the hanoi function to carry out the movement.

Note: The above code is provided as an example only and does not include input validation or error handling. In real-world applications, it is important to consider the validity of input and how errors are handled.

bannerAds