The structure of a recursive algorithm is as follows:
The conditions are usually some « if », they include stop conditions (do not return the function) or conditions of continuity (restart the function or return 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 as following (example for the calculation of a power):
Here is a simple example to calculate n!:
Here we see the fact that recursion behaves like a loop.
The mathematical program is as following(example for Pascal’s relation):
Which gives the following code:
Stack of execution
The execution stack of the current program is a memory location for storing parameters, local variables, and return addresses of functions that are running.
This stack operates on 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 while retaining the rest of the information in the stack, and it adds the new results at the top of the stack. Since it is LIFO, this last information will be read first, which is why it gives an impression of execution pyramid:
The execution stack of the Fibonacci suite follows the same principle:
We see here a rollercoaster effect due to the successive removal 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 path in depth (we go further in the successors) of the tree of its recursive calls:
Thus, the stack has nothing in memory throughout the recursion. This means that the value returned is directly the value obtained without there being any additional operation. Let’s take the example of the factorial recursively terminal:
This is exactly like writing the following loop: