recursion notes !! (1)
recursion notes !! (1)
2
Recursion
Recursion is deceptively simple in statement but exceptionally
complicated in implementation. Recursive procedures work fine in many
problems. Many programmers prefer recursion through simpler
alternatives are available. It is because recursion is elegant to use
through it is costly in terms of time and space. But using it is one thing
and getting involved with it is another.
A function is recursive if a statement in the body of the function calls itself. Recursion is
the process of defining something in terms of itself. For a computer language to be
recursive, a function must be able to call itself.
For example, let us consider the function factr() shown below, which computers the
factorial of an integer.
#include <stdio.h>
int factorial (int);
main()
{
int num, fact;
return (result);
}
factorial (int n)
{
int i, result = 1;
if (n == 0)
return (result);
else
{
for (i=1; i<=n; i++)
result = result * i;
}
return (result);
}
The operation of the non-recursive version is clear as it uses a loop starting at 1 and
ending at the target value and progressively multiplies each number by the moving
product.
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 the start.
A recursive call does not make a new copy of the function. Only the arguments and
variables are new. As each recursive call returns, the old local variables and parameters
are removed from the stack and execution resumes at the point of the function call
inside the function.
When writing recursive functions, you must have a exit condition somewhere to force
the function to return without the recursive call being executed. If you do not have an
exit condition, the recursive function will recurse forever until you run out of stack
space and indicate error about lack of memory, or stack overflow.
Iteration Recursion
Iteration explicitly user a repetition Recursion achieves repetition through
structure. repeated function calls.
Iteration terminates when the loop Recursion terminates when a base case
continuation. is recognized.
Iteration keeps modifying the counter Recursion keeps producing simple
until the loop continuation condition versions of the original problem until
fails. the base case is reached.
Iteration normally occurs within a loop Recursion causes another copy of the
so the extra memory assigned is function and hence a considerable
omitted.
time. time.
n = 0, 0 ! = 1 Base Case
n > 0, n ! = n * (n - 1) ! Recursive Case