Module: (C++) Recursion


Problem

1/12

Recursion. What is this?

Theory Click to read/hide

A procedure or function may contain a call to another procedure within it. Including, the subroutine can call itself. In this case, the computer doesn't care. He also, as always, consistently executes the commands that he met from top to bottom.

If you remember mathematics, then there you can meet the principle of mathematical induction. It is as follows:

some statement is true for every natural n if
    1. it is valid for n = 1 and
    2. from the validity of the statement for any arbitrary natural n = k it follows that it is true for n = k+1.

In programming, this technique is called recursion

Recursion is a way of defining a set of objects in terms of the set itself, based on given simple base cases.


Recursive will also be called a procedure (function) that calls itself directly or through other procedures and functions
An example of a recursive procedure:

void Rec(int a)
{
  if (a>0) Rec(a-1);
  cout << a;
}
Schematically, the work of recursion can be represented by a flowchart

 
The Rec() procedure is executed with parameter 3. Then, inside the procedure with parameter 3, the procedure with parameter 2 is called, and so on, until the procedure with parameter 0 is called. When the procedure with parameter 0 is called, the recursive call already will not happen and the procedure with parameter 0 will print the number 0 and terminate. Then control is transferred back to the procedure with parameter 1, it also finishes its work by printing the number 1, and so on. before the procedure with parameter 3. 

All called procedures are stored in memory until they complete their work. The number of concurrent procedures is called recursion depth.

Problem

Using the parsed procedure, add the necessary lines to the main program.
Understand why the program gives such a response