top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Tower of Hanoi Program in C

0 votes
588 views

Please help me with the tower of hanoi program in C using recursion?

posted Aug 25, 2014 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button
Google me khoj le yaar.....Search in Google first......
That's why it was asked as anonymous

1 Answer

+1 vote
 
Best answer

In Tower of Hanoi we have to move all the disc from (assumes you have 3 tower namely A, B, C) tower A to tower C, in the same order as the disc are on tower A, with the help of tower B.

#include <stdio.h>

void swap_towers(int, char, char, char);  //prototype for my recursive function.

int main()
{
    int num_disk;

    printf("Enter the number of disks :  ");
    scanf("%d", &num_disk);

    printf("Movement of disks (i.e form Tower A to Tower B) involved in the Tower of Hanoi are :\n");

    swap_towers(num_disk, 'A', 'C', 'B');

    return 0;
}

void swap_towers(int num, char from_tower, char to_tower, char ex_tower)
{
    if (num == 1) // Condition to stop the recursion.
    {
        printf("\nMove disk 1 from Tower %c to Tower %c", from_tower, to_tower);
        return;
    }

    swap_towers(num - 1,  from_tower, ex_tower, to_tower);

    printf("\nMove disk %d from Tower %c to Tower %c", num, from_tower, to_tower);

    swap_towers(num - 1, ex_tower, to_tower, from_tower);
}
answer Aug 25, 2014 by Arshad Khan
...