Recursivity.
Recursivity is the property that functions have to be called by themselves. It is useful for many tasks, like sorting
or calculate the factorial of numbers. For example, to obtain the factorial of a number (n!) the mathematical
formula would be:
n! = n * (n-1) * (n-2) * (n-3) ... * 1
more concretely, 5! (factorial of 5) would be:
5! = 5 * 4 * 3 * 2 * 1 = 120
and a recursive function to calculate this in C++ could be:
// factorial calculator
#include <iostream>
using namespace std;
long factorial (long a)
{
if (a > 1)
return (a * factorial (a-1));
else
return (1);
}
int main ()
{
long number;
cout << "Please type a number: ";
cin >> number;
cout << number << "! = " << factorial (number);
return 0;
}
Please type a number: 9
9! = 362880
Notice how in function factorial we included a call to itself, but only if the argument passed was greater than 1,
since otherwise the function would perform an infinite recursive loop in which once it arrived to 0 it would continue
multiplying by all the negative numbers (probably provoking a stack overflow error on runtime).
This function has a limitation because of the data type we used in its design (long) for more simplicity. The results
given will not be valid for values much greater than 10! or 15!, depending on the system you compile it.
long factorial (long a)
{
if (a > 1)
return (a * factorial (a-1));//here the function calls itself with as argument a-1
elsereturn (1);
}
The result of factorial(5) would be:
5 * ( 4 * ( 3 * ( 2 * ( 1 ) ) ) )
^ ^ ^ ^ ^
| | | | 5th time the function is called, argument = 1 so return 1
| | | 4th time the function is called (argument = 2)
| | 3rd time the function is called (argument = 4-1 = 3)
| 2nd time the function is called (argument = 5-1 = 4)
1st time the function is called argument = 5