Recursion
This lesson explains the concept of recursion using the factorial example
We'll cover the following...
What is Recursion? #
Recursion is a method of function calling in which a function calls itself during execution.
A recursive function must comprise of at least one base case i.e. a condition for termination of execution.
The function keeps on converging to the defined base case as it continuously calls itself.
Example #
Let’s start by showing an example and then discussing it.
Press + to interact
<?phpfunction factorial($n){if ($n == 1 || $n == 0){ //base casereturn 1;}else{return $n * factorial($n - 1); //function calls itself}}echo factorial(4); //calling the function with 4 as the argument?>
This is a classic application of recursion. This function calculates the factorial of a ...