Recursion - Explained By Me.

joel silva
3 min readJul 5, 2021

Recursion in Programming

What is recursion? Sometimes a problem is too difficult or too complex to solve because it is too big. If the problem can be broken down into smaller versions of itself, we may be able to find a way to solve one of these smaller versions and then be able to build up to a solution to the entire problem. This is the idea behind recursion; recursive algorithms break down a problem into smaller pieces which you either already know the answer to, or can solve by applying the same algorithm to each piece, and then combining the results.

Stated more concisely, a recursive definition is defined in terms of itself. Recursion is a computer programming technique involving the use of a procedure, subroutine, function, or algorithm that calls itself in a step having a termination condition, so that successive repetitions are processed up to the critical step where the condition is met at which time the rest of each repetition is processed from the last one called to the first.

How to Use Recursion

Now that we’ve established when to use recursion and when not to, let’s have a look at how we can implement it.

A recursive function requires two parts: a recursive call and a base case.

The recursive call is the part of the function that will keep calling itself.

The base case returns a value without making any subsequent calls. The function might have more than one base case, but it must have at least one. If not, your function will enter an infinite loop and your program will crash.

An example of an exercise:

I will explain what function each part of this exercise has so that you understand what it does

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);
}

In this code, we have the function

_pow_recursion(base, exp). This function could calculate the base to the exp power using recursion.

This is important because this is the break of the recursion, without it, the recursion could become into an infinity loop.

The code are going to call itself and decrementing the exponent by 1.

Additionally, the function returns the base times of the return of the recursion.

If you want to know more, Open a browser and type “recursion” on Google and dive into the world of recursion.

--

--