Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 1

Recursion is when a function calls itself. This circular definition can usually lead to neat algorithms.

The problem is broken down into a small task and then repeated many times. Recursion is rather common in mathematics and one example of this involves exponents. Consider the following recursive function:
function power($base, $exp) { // line 1 if ($exp) { // line 2 return $base * power ($base, $exp - 1); // line 3 } // line 4 return 1; // line 5 }

This complex little function is based on the recognition that the expression xy is equivalent to:

x * x(y-1)
We have broken a complex problem, say "4 to the power of 3", into two simpler problems: "4 times (4 to the power of 2)". And "4 to the power of 2" can itself be broken down as "4 times (4 to the power of 1)". While this process is rather complicated to follow, it does lead to an elegant solution. (However, it is often more efficient in terms of processing speed to use a loop in lieu of recursion.) Let's call the function and see what happens:
echo (power(4, 3));

1. The function power() is invoked. $base is set to 4, and $exp is set to 3. 2. In line 2, the value of $exp is tested. Since it does not equal zero, line 3 is executed. 3. Line 3 calls a second invocation of power(), passing 4 and 2 as its arguments. 4. In line 2 of the second invocation of power(), $exp still does not equal zero (it equals 2), so line 3 is executed. 5. Line 3 calls a third invocation of power(), passing 4 and 1 as its arguments. 6. In line 2 of the third invocation of power(), $exp still does not equal zero (it equals 1), so line 3 is executed. 7. Line 3 calls a fourth invocation of power(), passing 4 and 0 as its arguments. 8. Since $exp equals zero in the fourth invocation of the function, line 3 does not execute. Control passes to line 5,
which ceases execution of the fourth invocation and returns a value of 1. This value is passed back to line 3 of the third invocation of the function. 9. The value 1 is now substituted for the power() function in line 3. It is then multiplied by $base, resulting in a value of 4. The third invocation ceases and returns the value 4 to line 3 of the second invocation. 10. Line 3 of the second invocation of the function multiplies the value 4 by $base and returns this value (16) to line 3 of the original invocation of the function. 11. Line 3 of the original invocation of the function multiplies the value 16 by $base and returns the new value (64).

You might also like