"Welcome to our PHP 101 blog, where we demystify the world of web development. "

Tuesday, January 23, 2024

Recursive function in PHP

Recursive function in PHP

A recursive function in PHP is a function that calls itself during its execution. This process is known as recursion. Recursive functions are used to solve problems that can be broken down into smaller, simpler instances of the same problem.

Recursion is a powerful technique, and it's particularly suitable for solving problems where the solution to a larger instance of the problem can be derived from the solutions of smaller instances. It's important to ensure that there is a well-defined base case to prevent infinite recursion.

Example:

<?php
// Recursive function to calculate factorial
function factorial($n) {
    if ($n <= 1) {
        return 1; // Base case: factorial of 0 and 1 is 1
    } else {
        return $n * factorial($n - 1); // Recursive case
    }
}
// Example usage
$result = factorial(5);
echo "Factorial of 5 is: $result"; // Outputs: Factorial of 5 is: 120
?>

Output:
Factorial of 5 is: 120

Explanation:

  1. The factorial function is defined to calculate the factorial of a given number $n.
  2. It starts with a base case: if $n is less than or equal to 1, the function returns 1, as the factorial of 0 and 1 is 1.
  3. In the recursive case, if $n is greater than 1, the function returns $n multiplied by the result of calling itself with $n - 1.
  4. The factorial function is called with the argument 5 to calculate the factorial of 5.
  5. The result is stored in the variable $result.
  6. The echo statement outputs the result, indicating the factorial of 5.
  7. The initial call to factorial(5) triggers recursive calls until the base case is reached ($n <= 1).
  8. Each recursive call multiplies the current value of $n with the result of the next recursive call.
  9. The recursion unwinds, and the final result is obtained.
  10. The calculated factorial of 5 is 120.
  11. The echo statement outputs: "Factorial of 5 is: 120".

Output explanation:
step 1: 
Factorial Calculation:
The function factorial(5) is called.
It enters the recursive case and returns 5 * factorial(4).
step 2:
Recursive Calls:
The recursive calls continue:
factorial(4) returns 4 * factorial(3).
factorial(3) returns 3 * factorial(2).
factorial(2) returns 2 * factorial(1).
factorial(1) hits the base case and returns 1.
step 3:
Backtracking and Multiplication:
The recursion starts to unwind, and the results are multiplied as it backtracks:
2 * factorial(1) becomes 2 * 1 = 2.
3 * factorial(2) becomes 3 * 2 = 6.
4 * factorial(3) becomes 4 * 6 = 24.
5 * factorial(4) becomes 5 * 24 = 120.
step 4:
Final Result:
The final result is the factorial of 5, which is 120.
step 5:
Echo Statement:
The echo statement outputs: "Factorial of 5 is: 120".


No comments:

Post a Comment

Pages

SoraTemplates

Best Free and Premium Blogger Templates Provider.

Buy This Template