- [Narrator] In mathematics, a recursive function
is a function that refers to itself.
For example, a factorial indicated in mathematics
by the exclamation mark, is defined as the product
of all positive integers less than
or equal to its prime factor.
In other words, the factorial five
is equal to five times the factorial of four.
This is an example of recursion in mathematics.
Let's try it in C++ here is recursive factorial .CBP
from chapter five of the exercise files.
You notice we have here a function
that takes an unsigned long int called N
and if N is less than two, we just return one.
Otherwise, we return N times the factorial of N minus one.
So there's our recursion.
This function calls itself.
And when it calls itself with a argument
of less than two, it doesn't call itself again.
So that ends the recursive loop.
And here we call the function in main.
And if I build and run it says the factorial of five is 120,
which is the correct answer.
Now this is very clever
and it looks really cool and it's kind of simple,
but it's got its share of downsides.
For every recursive function call,
memory is allocated for the parameters,
for any local variables, for the return value
and for other function called overhead,
all on the stack.
So a loop is often more efficient.
C++ supports recursive functions,
but you need to be careful,
for problems that may require a lot of iterations,
recursion can quickly use up a lot of resources,
which can easily create buffer overflow
related security vulnerabilities.
And it's often better just to find a different solution.