Module: (C++) Recursion


Problem

2/12

Recursion. Cycle Simulation

Theory Click to read/hide

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); } }

Problem

Study the program below and arrange in the main program a procedure call with the parameters i=1, n=10. #include <iostream> using namespace std; //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); } } main() { // here it is necessary to issue a procedure call with parameters i=1, n=10. }