Recursive solutions for Fibonacci series and Towers of Hanoi.

C Program to Solve Tower-of-Hanoi Problem using Recursion

This C Program uses recursive function & solves the tower of hanoi. The tower of hanoi is a mathematical puzzle. It consists of threerods, and a number of disks of different sizes which can slideonto any rod. The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the smallest at the top. We have to obtain the same stack on the third rod.
Here is the source code of the C program for solving towers of hanoi. The C Program is successfully compiled and run on a Linux system. The program output is also shown below.
  1. /*
  2.  * C program for Tower of Hanoi using Recursion
  3.  */
  4. #include <stdio.h>
  5.  
  6. void towers(int, char, char, char);
  7.  
  8. int main()
  9. {
  10.     int num;
  11.  
  12.     printf("Enter the number of disks : ");
  13.     scanf("%d", &num);
  14.     printf("The sequence of moves involved in the Tower of Hanoi are :\n");
  15.     towers(num, 'A', 'C', 'B');
  16.     return 0;
  17. }
  18. void towers(int num, char frompeg, char topeg, char auxpeg)
  19. {
  20.     if (num == 1)
  21.     {
  22.         printf("\n Move disk 1 from peg %c to peg %c", frompeg, topeg);
  23.         return;
  24.     }
  25.     towers(num - 1, frompeg, auxpeg, topeg);
  26.     printf("\n Move disk %d from peg %c to peg %c", num, frompeg, topeg);
  27.     towers(num - 1, auxpeg, topeg, frompeg);
  28. }
$ cc pgm11.c
$ a.out
Enter the number of disks : 3
The sequence of moves involved in the Tower of Hanoi are :
 
Move disk 1 from peg A to peg C
Move disk 2 from peg A to peg B
Move disk 1 from peg C to peg B
Move disk 3 from peg A to peg C
Move disk 1 from peg B to peg A
Move disk 2 from peg B to peg C
Move disk 1 from peg A to peg C

No comments:

Post a Comment