RECURSION

Julieth Gonzalez
2 min readJul 4, 2021
Matryoshka Dolls

What is it?

Recursion is a process used in mathematics and programming in which a function calls itself, this method of repetition is understood with the principle of the Matryoshka (wooden doll that contains another smaller doll within itself, this doll, also contains another doll inside), where the problem is solved, treating the same problem but smaller.

Advantages and disadvantages

As disadvantages of using this method:

  • It is slower due to the overhead of holding the stack.
  • Uses more memory for the stack.

And the advantages:

  • Adds clarity and (sometimes) reduces the time it takes to write and debug code.
  • Reduce the complexity of time.
  • It performs best for solving problems based on tree structures.

Example: Factorial

A mathematical function solvable by recursion is the factorial, let’s see the following code:

float _pow_recursion(float x, float y)
{
if (y == 0)
return (1);
if (y < 0)
return (_pow_recursion(x, y + 1) / x);

return (_pow_recursion(x, y - 1) * x);
}

for this example we will assign the values ​​x = 2, y = 4.

Exercise flow chart

As evidenced, the exercise can be divided into two threads the first step when the value of y is greater than 0, where the function returns a decrease in the value of y , the second step when the value of y is equal to 0, which begins to be returned evaluating each value until it reaches the beginning.

on console

Thank you for reading

Julieth González - cohort 14(Holberton School)
Bogota, Colombia

--

--