C Program to create a solution to the Towers of Hanoi game

How to write a C Program to create a solution to the Towers of Hanoi game in C Programming Language ?


Solution:

  1. /* Program to create a solution to the Towers of Hanoi game*/


  2. #include <stdio.h>
  3. void SparePegAssign(int, int, int&);
  4. void TowerSolver(int, int, int, int);
  5. int main()
  6. {
  7.     int disk, fromPeg, toPeg, sparePeg = 1;
  8.     printf("Enter the number of disks you want to move: ");
  9.     scanf("%d", &disk);
  10.     printf("From which peg: ");
  11.     scanf("%d", &fromPeg);
  12.     printf("To which peg: ");
  13.     scanf("%d,", &toPeg);
  14.     SparePegAssign(fromPeg, toPeg, sparePeg);
  15.     printf("The sequence of moves involved in the Tower of Hanoi are : ");
  16.     TowerSolver(disk, fromPeg, toPeg, sparePeg);
  17.     return 0;
  18. }
  19. // Recursion function,
  20. void TowerSolver(int ldisk, int lfromPeg, int lnewPeg, int lsparePeg)
  21. {
  22.     if (ldisk == 1) { // If statement to determine if it will be the final move.
  23.         printf("\n Move a disk from peg %d to peg %d", lfromPeg, lnewPeg);
  24.         return;
  25.     }
  26.     else { // Used to the move the disks until ldisk results in a 1.
  27.         TowerSolver (ldisk - 1, lfromPeg, lsparePeg, lnewPeg);
  28.         printf("\n Move a disk from peg %d to peg %d", lfromPeg, lnewPeg);
  29.         TowerSolver(ldisk - 1, lsparePeg, lnewPeg, lfromPeg);
  30.     }
  31. }
  32. /* Function put in place to determine what the value of the spare peg will be.
  33.  * It does this by taking the sum of the other pegs
  34.  */
  35. void SparePegAssign (int lfromPeg, int ltoPeg, int& lsparePeg) {
  36.     if ((lfromPeg + ltoPeg) == 3)
  37.         lsparePeg = 3;
  38.     else if ((lfromPeg + ltoPeg) == 4)
  39.         lsparePeg = 2;
  40.     else
  41.         lsparePeg = 1;
  42.     return;
  43. }


Learn More :