The structure of a algorithm recursive is:
The conditions are generally ifs, they include the stop conditions (does not return the function) or continuity conditions (relaunches the function or returns the function). The continuity conditions modify the inputs of the restarted function. A recursive function must have at least one stop condition.
The mathematical program is of the following type (example for the calculation of a power):
Here is a simple example to calculate the factorial of n:
Here we can see the fact that recursion behaves like a loop.
The mathematical program is of the following type (example for Pascal's relation):
Will give for program:
The stack of execution of the current program is a memory location intended to memorize the parameters, the local variables as well as the return addresses of the functions being executed.
This stack works according to the LIFO (last in first out) principle and has a fixed size. Here is the stack for the simple factorial, as soon as the program reads a method, it executes it, keeping the rest of the information on the stack, and it adds the new results to the top of the stack. Since it is LIFO, this last piece of information will then be read first, which is why it gives the impression of an execution pyramid:
The Fibonacci sequence execution stack follows the same principle:
We clearly see here a roller coaster effect due to the successive popping of the function on the left as soon as it is encountered. It is easier to represent the stack of a multiple recursive function by a in-depth journey (we go the farthest in the successors) of its recursive call tree:
Thus, the stack has nothing in memory throughout the recursion. This means that the returned value is directly the value obtained without there being any additional operation. Let us take the example of the factorial in a terminal recursive way:
This is exactly the same as writing the following loop: