Recursion refers to the property of some concepts to be defined in terms of themselves.
In C++, recursion is achieved through functions that can call themselves. Recall that a function must be defined and then can be called. Recursion consists of the fact that in the definition of a function, the function itself is called. This call, which appears in the very definition of the function, is called a self-call. The first call, made in another function, is called the main call.
Let's write a C++ function that returns the factorial of a natural number passed as a parameter. The non-recursive (iterative) version is as follows:
int fact(int n)
{
int p = 1;
for(int i = 1 ; i <= n ; i ++)
p = p * i;
return p;
}
We observe that this function determines the correct result for values of n greater than or equal to 0 (small values, practically n <= 12). The function also correctly determines the result for n == 0.
A recursive version for determining n!, which uses the observations above, is:
int fact(int n)
{
if(n == 0)
return 1;
else
return n * fact(n-1);
}
The self-call is made according to the header of the recursive function. Thus:
void fact(int n, int &r)
{
if(n == 0)
r = 1;
else{
fact(n - 1 , r);
r = r * n;
}
}
int main()
{
int a;
fact(4, a);
cout << a;
return 0;
}
int fact(int n)
{
int r;
if(n == 0)
r = 1;
else
r = n * fact(n - 1);
return r;
}
int main()
{
int a;
a = fact(4);
cout << a;
return 0;
}
In this section you can generate a summary of the page content using AI! Feel free to use the button below whenever you are in a hurry and don't have time to learn everything!
In this section you can ask our expert robot anything related to the questions you encountered during the lessons! Feel free to use the button below whenever you need additional explanations!