Recursion versus iterative algorithms

If we analyze our factorial function, we can see that it could be written using a simple iterative approach with a for or while loop, as shown here:

function factorial(int $n): int { 
$result = 1;

for ($i = $n; $i > 0; $i--) {
$result *= $i;
}

return $result;
}

If this can be written as a simple iterative one, then why should we use recursion? Recursion is used to solve more complex problems. Not all problems can be solved iteratively so easily. For example, we need to show all the files in a certain directory. We can simply do this by running a loop to list all the files. However, what if there is another directory inside it? Then, we have to run another loop to get all those files inside that directory. What if there is another directory inside that directory and it goes on and on? In such a situation, an iterative approach might not help at all or might create a complex solution. It is better to choose a recursive approach here.

Recursion manages a call stack for managing function calls. As a result, recursion will take more memory and time to complete compared to iteration. Also, in iteration, in each step, we can have a result, but for recursion, we have to wait until the base case to execute to get any result. If we consider both iterative and recursive examples for a factorial, we can see that there is a local variable called $result to store the calculation of each step. However, in recursion, there is no need for local variables or assignment.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset