Recursion. Loop Simulation
We have seen that recursion is the repeated execution of contained instructions in a subroutine. And this, in turn, is similar to the work of the cycle. There are programming languages in which the loop construct is absent at all, for example, Prolog.
Let's try to simulate the work of the loop
for
.
The
for
loop contains a step counter variable. In a recursive subroutine, such a variable can be passed as a parameter.
// Procedure LoopImitation() with two parameters.
// First parameter – step counter, second parameter – total number of steps.
void LoopImitation(int i, int n)
{
cout << "Hello N" << i << endl; // Operator to be repeated for any value of i
if (i < n) // Until loop counter equals n,
{ // call a new instance of the procedure, with the parameter i+1 (go to the next value i).
LoopImitation(i + 1, n);
}
}