An Introduction to Recursion

Johnson Liu
3 min readMay 24, 2021

--

What is recursion?

Google’s play on the word recursion

To put it bluntly, the word itself is a running joke. The second you search it up on Google, you will get this message asking if you mean recursion, even though you spelled it correctly. This right here is the epitome of the meaning recursion. If you click on the suggested word, you will end on the same page over and over again. It is literally describing the meaning of the word; something happing over and over again. When you begin your search on recursion, you will always run in to the endless memes and jokes on it.

Sierpinski Triangle

To give some additional examples of recursion, we can take a look at Sierpinski’s triangle above. To draw Sierpinski’s triangle, you need to draw and upside down triangle in the middle to create four smaller ones. Then you repeat the process for the three right side up triangles within the main triangle. Then you repeat again and again in each smaller triangle inside. As you get smaller, the triangles start looking like dots.

Another example of recursion is a factorial. In each factorial below, you are performing the same action over again.

One of the most common themes used to understand recursion is using a countdown.

Countdown with While loop

At this point, you should be familiar with for and while loops. Above is a simple while loop count down from 10. This will return each value from ten to zero. Now let us see how we can implement this with recursion.

Countdown with Recursion

Above we setup a similar function. The countDown function simply logs in the console the number passed in an argument down to zero. With the recursive case as you can see, we are simply calling the function within itself until we stop at zero. If you change the zero to a negative number like -10, it would count from ten to negative 10. Next time we will look at a more complex problem.

--

--

Johnson Liu
Johnson Liu

No responses yet