Sunday, January 11, 2009

RECURSION - Joannacel Paraiso

RECURSION
  • l
    lThe repetitive process by which a functions calls itself is called recursion or circular definition.
  • lThis is a way of defining something in terms of itself.
  • lA function is said to be recursive if a statement in the body of the function calls the function that contains it.
Parts of recursive function

**BASE CASE
-
This is the part of the recursive function that is found on the if clause. This contains the condition that should be satisfied at one point of execution to terminate the repetitive process done by the recursive function.

**GENERAL CASE
-
This is the part of the recursive function that is found on the else-clause. This contains the function call of the recursive function to itself.



factorial (int n)
{
if (n == 1 || n == 0) return 1;

else return (n * factorial (n-1));
}

If n value is 4 ,
4 * (factorial (4-1)
If n value is 3,
3 * (factorial (3-1)
If n value is 2, 2 * (factorial (3-1)
If n value is 1, 1


factorial (int n)
{

if (n == 1 || n == 0) return 1;
else return (n* factorial (n-1));
}

Simplifying the Expression....

4 * (factorial (4-1) = 24 general case
3 * (factorial(3-1) = 6 general case
2 * (factorial(2-1) = 2 general case
1 base case

Therefore, the final return value when n=4 is 24.

Direct and Indirect Recursion
  • Direct recursions are cursive functions that can call itself through a functioncall directly inside the body of the function.
  • Indirect recursions are cursive functions that can call another functions outside the function.














No comments: