Tower of Hanoi C Code Recursive

Here is an example of a recursive algorithm code for the Tower of Hanoi problem in the C language.

#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 code above implements the solution to the Tower of Hanoi problem using recursion. The function hanoi takes parameters n for the number of disks to be moved, from for the starting rod, to for the target rod, and aux for the auxiliary rod. In each recursive step, n-1 disks are moved from the starting rod to the auxiliary rod, then the last disk is moved from the starting rod to the target rod, and finally n-1 disks are moved from the auxiliary rod to the target rod. The main function inputs the number of disks and calls the hanoi function to solve the problem.

bannerAds