This week we just tackled about RECURSION. Recursion defined as the repetitive process by which a functions calls itself is called recursion or circular definition. This is a way of defining something in terms of itself. A function is said to be recursive if a statement in the body of the function calls the function that contains it.
Parts of the 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.
Example 1 (This Example was given to us by our TLE teacher, Mr. Ernie Balbuena )
factorial (int n)
{
if (n == 1 || n == 0) return 1;
else return (n * factorial (n-1));
}
If the n value is 4, 4 * (factorial (4-1)
if the n value is 3, 3 * (factorial (3-1)
if the n value is 2, 2 * (factorial (2-1)
if the 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.