I know that recursion is a technique to call a function within the function itself.
but the below code confuses me on how it is able to do the cout part after the first recursion:
(This code solves the tower of hanoi puzzle)
#include <iostream>
using namespace std;
void move_rings(int n, int src, int dest, int other);
int main(void)
{
int rings;
cout << "Number of Rings: ";
cin >> rings;
move_rings(rings, 1, 3, 2);
system("PAUSE");
}
void move_rings(int rings, int source, int destination, int other)
{
if (rings == 1)
{
cout << "Move from " << source << " to " << destination << endl;
}
else
{
move_rings(rings - 1, source, other, destination);
cout << "Move from " << source << " to " << destination << endl;
move_rings(rings - 1, other, destination, source);
}
}
As you can see, the function move_rings calls itself after the if statement.
When I visualize this, I see a never ending loop… How is it possible for this function to do the
cout << "Move from " << source << " to " << destination << endl;
part?
The output of the program is this:
Move from 1 to 3
Move from 1 to 2
Move from 3 to 2
Move from 1 to 3
Move from 2 to 1
Move from 2 to 3
Move from 1 to 3
Recursion can be a bit tough to grasp at first. It “clicked” for me when I thought about it like this: you have a base case, which is the condition that will lead the recursive function not to call itself anymore, and then you have the other part (“else” in your code), where the function will continue to be called. The “rings == 1” condition is your base case.
The function “move_rings” gets called with a smaller argument each time. In each subsequent call, the variable “rings” gets smaller (and therefore “moves closer” to the base case), until “rings == 1” is true, and then the function stops calling itself.
Hope that helps.