Recursion

--Originally published at Programming

Definition

It’s time to start taking on more advanced topics. Recursion is a way to code a problem, in which a function calls itself several times withing its body. In mathematical terms a recursive function is a function that is defined in terms of itself. If a function fulfills the definition of recursion, it is then called a recursive function.

Terminate a recursive function

A recursive function needs to be terminated in a program. A recursive function is terminated when the solution of the problem is reduced and reaches a base case. A base case is defined as the case when the problem doesn’t require further recursion in order to be solved.

Example

The factorial of a number would be a recursive problem. A simple way to make a program to get the factorial of a number n is on the left, and on the right we can find the same problem using recursion.

2.png1.png

 

 

 

Let’s track how the recursive function works by adding print functions to the previous function definition.

3.png

4.png

If you want to learn deeper about this topic I recommend you to read the following article that explains how to use recursion. http://openbookproject.net/thinkcs/python/english3e/recursion.html