4.DS -LAB - C Program to implement Towers of Hanoi(Part A)

 C Program to implement Towers of Hanoi

ALGORITHM :

Step 1: Start
Step 2: Declare a function towers_of_hanoi(n, source, auxiliary, destination).
Step 3: If n is equal to 1, then
            a. Print "Move disk 1 from source to destination."
            b. Return
Step 4: Recursively call towers_of_hanoi with n-1 disks, source, and auxiliary as new parameters.
Step 5: Print "Move disk n from source to destination."
Step 6: Recursively call towers_of_hanoi with n-1 disks, auxiliary, and destination as new parameters.
Step 7: Input the number of disks (num_disks) to move.
Step 8: Call towers_of_hanoi with num_disks, 'A' (source), 'B' (auxiliary), and 'C' (destination) as initial parameters.
Step 9: End

SOURCE CODE :

#include <stdio.h>
void towersOfHanoi(int n, char source, char auxiliary, char destination) {
    if (n == 1) {
        printf("Move disk 1 from %c to %c\n", source, destination);
        return;
    }
    towersOfHanoi(n - 1, source, destination, auxiliary);
    printf("Move disk %d from %c to %c\n", n, source, destination);
    towersOfHanoi(n - 1, auxiliary, source, destination);
}

int main() {
    int numDisks;
    printf("Enter the number of disks: ");
    scanf("%d", &numDisks);

    towersOfHanoi(numDisks, 'A', 'B', 'C');

    return 0;
}


OUTPUT :

Enter the number of disks: 3
Move disk 1 from A to C
Move disk 2 from A to B
Move disk 1 from C to B
Move disk 3 from A to C
Move disk 1 from B to A
Move disk 2 from B to C
Move disk 1 from A to C

No comments:

Post a Comment