121 Week 9 - Recursion Flashcards
Iteration and recursion
Used to traverse a set of values or run the same logic a given number of times.
Any recursive solution can be written in an iterative way.
Any iterative solution can be written in a recursive way.
Iteration
A function which uses loops to execute the same logic multiple times.
Recursion
A function which calls itself to execute the same logic multiple times.
Order of execution in recursion.
The order in which logic is executed in recursion depends on if the logic is before or after the function calls itself.
Single recursion
A recursive function where you only need to have one self-call for each function call.
It is generally easy to write iteratively.
Multiple recursion
A recursive function where you need to have more than one self-call for each function call.
It is generally harder to write iteratively because we need to explicitly track state.
Reasons to use iteration
Memory usage is controlled explicitly by the programmer, so a “stack overflow“ less likely.
Can executes more quickly, as there is no overhead from stack frame creation / destruction.
Iterative functions can be easier to understand than a recursive function.
Reasons to use recursion
Recursive functions are much more concise than iterative functions.
Languages which support tail recursion can eliminate some of the extra cost to performance, and stack overflows.