DEV Community

Cover image for Recursion explained πŸŽ‰
Ben Matt, Jr.
Ben Matt, Jr.

Posted on

Recursion explained πŸŽ‰

In this article we will break down all the concept you need to know before saying that you fully understand recursion. The goal is to talk about those concepts so that you can come up with your own definition of what recursion is πŸ˜‹.

Definition : Recursion is mostly described as a process that calls it self.
It can also be described by a function that calls it self.

Call Stack : In case we're calling a function or more multiple times in a program,
their is a thing called "Call Stack" that is an actual stack in witch functions are placed
on top of each other in terms of execution,
so the call stack can hold informations about all the functions that are placed on it.

So when using a recursive function what happen is we keep pushing the same function onto the "Call Stack".

What's the main structure of a recursive function ? :

A recursive function has two essential parts wich are the base case and a different input (or function argument).

1) The base case :
For the base case you can, think of it as a condition that causes the function to stop calling it self, in other words it stops the recursion.

2) Different input : Everytime a recursive function is being called, we need to make sure that the input aren't the same.

If one of the two or both are missing the process can resolve in what called a
"Stack overflow" forcing you to spend hours looking for answers on stackoverflow.com πŸ˜‰.

Now let play a game!

The followings are two examples of recursive functions and your goal is to.
1) Find the "base case".
2) Find the the difference input.
3) Leave your answers in the comment section πŸ˜‹.

Ex 1:

Alt Code example

Ex 2:

Alt Code example

Top comments (1)

Collapse
 
iamntz profile image
Ionut Staicu • Edited

You can find more details about recursion here.