I recently stumbled on a question on Quora where someone asked if he could solve the Tower of Hanoi problem using iteration instead of recursion. I noticed 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:
and here?s an example of iteration:
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.
These are some of the key differences between iteration and recursion. I hope this has been explanatory.