Recursion and how it works on the stack

Blender Recursion GIF By Adampizurny — http://gph.is/2iOSPvH

What is recursion?

Recursion is defined as a function that calls itself.

What is the object or what is it used for?

It can be used in any situation in which the solution can be expressed as a sequence of movements, steps or transformations governed by a set of unambiguous rules.

  1. The problem is solved by treating the same problem of smaller size
  2. The way in which the size decreases ensures that the base case will eventually be reached
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);
}
int main (void)
{
float x;

x = _pow_recursion (2, 3);
return (EXIT_SUCCESS);
}
Image for post
Image for post
Image for post
Image for post
int main (void)
{
float x;

x = _pow_recursion (3.5, 3.8);
return (EXIT_SUCCESS);
}
Image for post
Image for post

Will it ever get to 0?

Segmentation fault! Here, we see that we have encountered a stack overflow. What does this mean? As we mentioned earlier, stack overflow occurs when we use up all the available storage that has been allocated to the stack-based memory allocation.

Why did this happened?

Because our value y cannot reach the base case (y == 0), our recursive calls can never cease until the stack memory is exhausted.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store