How to write a C Program to create a solution to the Towers of Hanoi game in C Programming Language ?
Solution:
/* Program to create a solution to the Towers of Hanoi game*/
- #include <stdio.h>
- void SparePegAssign(int, int, int&);
- void TowerSolver(int, int, int, int);
- int main()
- {
- int disk, fromPeg, toPeg, sparePeg = 1;
- printf("Enter the number of disks you want to move: ");
- scanf("%d", &disk);
- printf("From which peg: ");
- scanf("%d", &fromPeg);
- printf("To which peg: ");
- scanf("%d,", &toPeg);
- SparePegAssign(fromPeg, toPeg, sparePeg);
- printf("The sequence of moves involved in the Tower of Hanoi are : ");
- TowerSolver(disk, fromPeg, toPeg, sparePeg);
- return 0;
- }
- // Recursion function,
- void TowerSolver(int ldisk, int lfromPeg, int lnewPeg, int lsparePeg)
- {
- if (ldisk == 1) { // If statement to determine if it will be the final move.
- printf("\n Move a disk from peg %d to peg %d", lfromPeg, lnewPeg);
- return;
- }
- else { // Used to the move the disks until ldisk results in a 1.
- TowerSolver (ldisk - 1, lfromPeg, lsparePeg, lnewPeg);
- printf("\n Move a disk from peg %d to peg %d", lfromPeg, lnewPeg);
- TowerSolver(ldisk - 1, lsparePeg, lnewPeg, lfromPeg);
- }
- }
- /* Function put in place to determine what the value of the spare peg will be.
- * It does this by taking the sum of the other pegs
- */
- void SparePegAssign (int lfromPeg, int ltoPeg, int& lsparePeg) {
- if ((lfromPeg + ltoPeg) == 3)
- lsparePeg = 3;
- else if ((lfromPeg + ltoPeg) == 4)
- lsparePeg = 2;
- else
- lsparePeg = 1;
- return;
- }