Search

Recursive vs Iterative Functions

Iteration vs Recursion


The concepts can sometimes be used interchangeably and they are very similar.


The concept of Recursion and Iteration is to execute a set of instructions repeatedly. The difference between them is that recursion is simply a method call in which the method being called is the same as the one making the call while iteration is when a loop is repeatedly executed until a certain condition is met. Under the hood, both recursion and iteration depends on a condition so as to know when to stop but recursion is simply a process, always applied to a function.


An example of recursion is shown below:

function factorial(number) { 
    if (number === 1) { 
        return 1; 
    } 
    return number * factorial(number - 1);
}
view rawrecursion.js hosted with ❤ by GitHub

and here’s an example of iteration:

var step;
for (step = 0; step < 5; step++) { 
// Runs 5 times, with values of step 0 through 4. 
console.log('Walking east one step');
}
view rawiteration.js hosted with ❤ by GitHub

Key Differences between Recursion and Iteration


  • A conditional statement decides the termination of recursion while a control variable’s value decide the termination of the iteration statement (except in the case of a while loop).

  • Infinite recursion can lead to system crash whereas, infinite iteration consumes CPU cycles.

  • Recursion repeatedly invokes the mechanism, and consequently the overhead, of method calls. This can be expensive in both processor time and memory space while iteration doesn’t.

  • Recursion makes code smaller while iteration makes it longer.


Memoization makes recursion palatable, but it seems iteration is always faster. Although recursive methods run slower, they sometimes use less lines of code than iteration and for many are easier to understand. Recursive methods are useful for certain specific tasks, as well, such as traversing tree structures.

Recent Posts

See All

Dijkstra shortest path algorithm

Word ladder game (change only one letter to go from Fool to Sage): Fool, Pool, Poll, Pole, Pale, Sale, Sage. How? Dijkstra shortest path algorithm

Deep Learning for Algorithmic Trading

Finance is highly nonlinear and sometimes stock price data can even seem completely random. Machine learning and Deep Learning have found their place in the financial institutions for their power in p

Statistical Arbitrage Trading Pairs

What are z score values? A Z score is the value of a supposedly normal random variable when we subtract the mean and divide by the standard deviation, thus scaling it to the standard normal distributi

©2020 by Arturo Devesa.