Discussion - Recursion
Create a Hanoi Tower program (You can use the worked example) Explain in plain English how this program works and how it demonstrates the use of recursion Include a link to a repl.it file of your working program.
(c++)
Tower of Hanoi is kind of mathematical puzzle where we can have
3 rods and N disks.Main objective of this puzzle is to move the
entire stack to another rod, following 3 simple rules which are as
follows:
1) At a time, we can move only one block.
2) Each move will consist of taking the topmost disk from one of
the stacks, and placing it on top of another stack i.e. a disk can
be moved only if it is the topmost disk on a stack.
3) larger sized disk cannnot be placed on the smaller sized
disk.
take help from the below image, you will get the concept.
#include <bits/stdc++.h>
using namespace std;
void hanoiTower(int n, char from_stick, char to_stick, char aux_stick)
{
if (n == 1)
{
cout << "Moving disk 1 from stick " << from_stick <<" to stick " << to_stick <<endl;
return;
}
hanoiTower(n - 1, from_stick, aux_stick, to_stick);
cout << "Moving disk " << n << " from stick " << from_stick << " to stick " << to_stick << endl;
hanoiTower(n - 1, aux_stick, to_stick, from_stick);
}
// Driver code
int main()
{
cout << "Enter total number of disks ";
int k;
cin >> k;
hanoiTower(k, 'A', 'C', 'B'); //here we are asssuming A, B, C as three available three stick
return 0;
}
our main aim here is to transfer all the disks from stick A to stick C.
Run this program and try to ananlize each line of the output, you will get the better picture
for any further doubt, comment below. i would be more then happy to help you out.
Get Answers For Free
Most questions answered within 1 hours.