A function is called recursive if a statement in the body of the function calls itself. Recursion is the process of defining something in term if itself. C functions may be used recursively; that is, a function may call itself either directly or indirectly.
If fun1 () and fun2 () are two functions. Then
the direct call structure is
fun1 ()
{
.
.
Fun1 ()
.
.
}
i.e., function fun1 () calls itself directly.
and indirect call structure is
fun1 ()
{
.
.
fun2 ();
.
.
}
and
fun2 ()
{
.
.
fun1 ();
.
.
}
the function fun1 () calls itself indirectly, i.e. function fun1 () calls fun2 () and fun2 () once again calls function fun1().
let us consider the case of calculation of factorial value of a non – negative integer n.
n! = n X (n-1) X (n-2. . .X 3 X 2 X1
or n! = n X (n-1)!
The last expression is the recursive description of the factorial where as the fast is the iterative definition.
int factorial (int n)
{
if (n == 0)
fact = 1
else
fact = n * factorial (n-1);
return fact;
}
Here, the statement fact = n * factorial (n-1); recursively defines the factorial of an integer n. This is actually a direct translation of n! = n X (n-1)! in the form of factorial (n) n* factorial (n-1). This definition implies that n! will be calculated if (n-1)! Is known which in turns if (n-2)! is known and so on until n=0 when it returns 1. For an illustration, let us consider the calculation of 5! using recursive definition. To do this following step are needed:
Steps
When a function calls itself, new local variables and parameters are allocated storage on the stack and the function code is executed with these new variables from start. A recursive call does not make a new copy of the function. Only the arguments are new. As each recursive call return, the old local variables the parameters are removed from the stack and execution resumes at the point of function call inside the function.
Most recursive routines do not significantly reduce the code size or improve memory utilization. Also, the recursive versions of most routines may execute a bit slower than their iterative equivalent because of the repeated function calls.
In fact, many recursive calls to a function could cause a stack overrun. Because storage for function parameters and local variables is on the stack and each new call creates a new copy these variables, the stack could possibly overwrite some other data or program memory.
The main advantage to recursive functions is that you can them to create clearer and simple versions of several algorithms.
About the Author
Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.
We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc