Understanding Recursion
A concept that is notoriously difficult to grasp with entry-level programmers is recursion. The reasons for this are plentiful, but from my personal experience it took a while to click due to the potential found in the iteration of loops, which is capable of performing so many tasks. However, nested loops and other complexities surrounding iterative programming can take up many lines of code and be difficult to comprehend what process is taking place. This is where recursion can come in handy, which is simply “defining a problem in terms of itself”. More specifically, recursive functions have 3 primary attributes:
- A base case.
- A call to itself.
- Work towards the base case.
By call to itself, it means the name of the function will appear within the function. This is so we don’t have to repeat the prior code for the number of times the task will be performed.
I want to share the function which made recursion click for me; the goal is to write a function which returns the value of a positive number in the Fibonacci sequence given its position from 1, so, with 13 being the 7th number in the sequence, will return 13 when 7 is entered. The way to write this recursively is like this:
function fibSeq(int) {
if(int >= 3) {
return fibSeq(int-2) + fibSeq(int-1)
} else {
return 1
}
}
Per the sequence, the following number will always be a combination of the previous two numbers so long as the value is 3 or above. 1 is simply 1, and the second position of the sequence is also 1 because it combines 0 and 1. The base case is 1 as declared within the “else” statement. Every time the function is called, it will perform the operation of subtracting 1 and 2 from the input constituently and adding those integers together. Amazing, right?!
I hope I helped illuminate this concept a bit to you. It is a very strange and self-referential idea at first, but I guarantee, the more it is studied the more it makes sense, and the more the potential illuminates itself your way!