What is Recursion

In computer programming, recursion is usually labeled a rather difficult topic (especially for students), but its rather simple. Simple concepts are not necessarily easier to implement, because it depends the extend follows the normal way of thinking. A recursive function is no more than a function that references itself within its own definition, in such a way that a chain of references is created. Usually, a recursive function has a stop clause in such a way that stops calling itself ad infinitum.

Let me give you an example, this is an iterative function that receives an integer number and returns its factorial.

int FactorialIterative ( int input )
int x, fact = 1;
for ( x = input; x > 1; x--)
fact *= x;
return fact;

And now we have the recursive version:

public int FactorialRecursive(int n)
if (n==0) return 1;
else return n * FactorialRecursive(n - 1);

Which one seems easier to you? Probably the second but the natural way of thinking would lead you to write the first.
Recursion is really useful for solving certain types of problems, e.g. working with trees
For example:

n! = n * (n-1)!
could be expressed as: 6! = 6 * 5 !
then: 6! = 6*5*4 !
and so on…


There are many examples of recursion in the real world, like Matryoshka Dolls. These are dolls that are nested inside each other. And even memes !

Matrioska Dollsmemerecursion