How I learned the concept of recursion with two simple examples

A couple weeks ago I failed my first technical challenge. Core concepts of the challenge included closure, currying, recursion. I will talk about how I’ve learned recursion since the interview.

Recursion is a simple concept but can be confusing to grasp. My interview question was to create a function that recursively calculates the multiplication of two arguments foo and bar — without using multiplication or division.

The trick here is to understand that foo X bar is equal to foo plus itself bar number of times. Ex: multiply(3,4) = 3*4; and also multiply(3,4) = 3 + 3 + 3 + 3; Three plus itself four times. Now for the recursive function itself. The idea is to add foo to itself bar number of times and decrease it until we get to 1.

Another foundational example is using recursion to find the factorial of x. Denoted x! For example 5! or 5 factorial is the result of 5x4x3x2x1 = 120. To write it recursively. The base case is if n ≤ 1 return that value otherwise return the result of n * factorial(n-1). Example:

Like what you read? Give Kevin Kabore a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.