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;
- }
Learn More :
Create
- How To Write a C program that creates customers' bills for a carpet company when the following is given ?
- C Program to Create VIRUS
- Creates new main.c with empty main boilerplate template
- C Program to Create a copy of an image
- Ardunio: Create a crystal ball to tell you the future C Program
- C Program to Creating pico device
- Add x and y coordinates to create a new struct in C Program
- C program allocates new nodes and creates a four element list with fixed values
- C Program To Create Two Singly Linked List and Perform Following Operation
- Create Two Singly Linked List Perform Differences Display It C Program
- C Program Implement Binary Search Tree And Its Traversals
- C Program to Create, Display, Insert and Deletion of Queue Elements
- Creation and Display of Elements in Both Forward and Reverse Direction in a Doubly Linked List
- Calculator Using IF-ELSE in C Program