I am testing some codes related to recursion function. I saw the recursion method for towers of hanoi problem but I am very confused, two recursive functions are using in if condition. The understanding of the program till now is first it set n to zero and after this I dont know how it increases the n and how it knows which recursive function it should call first. I am weak in understanding of recursive function,please help me in understanding the working of recursive function of given program.
// Recursive Towers of Hanoi
#include <iostream>
using namespace std;
void towersOfHanoi(int n, int x, int y, int z)
{// Move the top n disks from tower x to tower y.
// Use tower z for intermediate storage.
if (n > 0) // Base Case
{
towersOfHanoi(n - 1, x, z, y);
cout << "Move top disk from tower " << x << " to top of tower " << y << endl;
towersOfHanoi(n - 1, z, y, x);
}
} // Recursive Procedure
void main(void)
{
cout << "Moves for a three disk problem are" << endl;
towersOfHanoi(3, 1, 2, 3);
system("pause");
}
Your understanding is pretty wrong.
It first set n
to zero. Actually it first sets n
to 3
towersOfHanoi(3, 1, 2, 3);
- this sets n
to 3 (first argument)
I don't know how it increases n
. Actually it decreases n
,
towersOfHanoi(n - 1, z, y, x);
- this sets n
to n - 1
(first argument again).
how it knows which recursive function it should call first?. It calls the first one first, same as any other code.
towersOfHanoi(n - 1, x, z, y); // THIS ONE FIRST
cout << "Move top disk from tower " << x << " to top of tower " << y << endl;
towersOfHanoi(n - 1, z, y, x); // THIS ONE SECOND
Recursive functions work exactly the same as any other functions. There is no magic.