DEV Community

ai-yugi
ai-yugi

Posted on

What is Recursion in Programming?

Recursion is a programming concept where a function calls itself either directly or indirectly to solve a smaller instance of the same problem. This is done by breaking down a larger problem until a base case that can easily be solved is reached.

Okay, that might have been a mouthful; in other words, a recursive function is a function that performs a task in part and delegates the remaining task to a new invocation of itself.

Example;
For instance you want to write a function that calculates the factorial of a number where the factorial of a non-negative integer n is the product of all positive integers less than or equal to n.

Let’s start by seeing how this problem can be solved using a non recursive function first;

Image description

Now here’s the solution using a recursive function;

Image description

Thanks for reading.

Top comments (0)