C Program for Tower of Hanoi Sequence

Subject: PPS (Programming for Problem Solving)

Contributed By: Sanjay

Created At: February 3, 2025

Question:


Write a C Program for Tower of Hanoi Sequence

Explanation Video:

Custom Image

Explanation:

 

  1. The Tower of Hanoi problem consists of moving n disks from a source rod to a destination rod using an auxiliary rod.

  2. The recursive function moves n-1 disks to the auxiliary rod before moving the last disk.

The base case occurs when there is only one disk to move.

Source Code:
#include <stdio.h>

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

int main() {
    int n;
    printf("Enter number of disks: ");
    scanf("%d", &n);
    towerOfHanoi(n, 'A', 'B', 'C');
    return 0;
}
Input:
Enter number of disks: 3
Output:
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
Share this Article & Support Us:
Status
printf('Loading...');