Professional Documents
Culture Documents
Introduction
Recursion Basics. Some computer programming languages allow a module
or function to call itself. This technique is known as recursion. In recursion,
a function either calls itself directly or calls a function that in turn calls
the original function is called recursive function.
Example a function calling itself.
int function(int value)
{
if(value < 1)
return;
function(value - 1);
cout<<value;
}
Example a function that calls another function
which in turn calls it again.
int function(int value)
{
if(value < 1)
return;
function(value - 1);
cout<<value;
}
Implementation:
Function Call
A Recursive function is a function that makes a call to itself. To
prevent infinite recursion, you need an if-else statement (of
some sort) where one branch makes a recursive call, and the
other branch does not. The branch without a recursive call is
usually the base case (base cases do not make recursive calls
to the function).Functions can also be mutually recursive. For
example, function f() can call function g() and
function g() can call function f(). This is still considered
recursion because a function can eventually call itself. In this
case, f() indirectly calls itself.
Recursive methods are either Tail
recursive or Non-tail recursive.
Definition: Tail recursive method has the recursive
call as the last statement in the method. Recursive
methods that are not tail recursive are called non-
tail recursive.
// An example of tail recursive function
void cout<<int n
{
if (n < 0)
return;
cout << " " << n;