What is Recursion?

James Ng
3 min readMay 14, 2022

Recursion is the process in which a function invokes itself again. In other words, it repeats the same action(s). Think of a live actor who repeats the same act show after show to a different audience each time until the last showtime.

In programming, a recursive function calls itself over and over again until a certain condition is satisfied. The syntax for a recursive function is:

Let us take a look at an example of how it works. The following function recurse(n) takes a single number n and applies the recursion concept by adding up all the numbers that decrement by 1 until the function reaches 1, the condition that ends the function. This condition will be discussed further at the end of this read.

In this case, the number (argument) n=10 is passed into the function. The computer tests the if statements and finds that the else if statement is true, hence it returns 10 + recurse(9).

***FOR ILLUSTRATION PURPOSES. NOT ACTUAL SYNTAX***

In recurse(9), n = 9 is passed through as an argument this time and the function is invoked (ran) again. Again, the computer tests the if statements returns the value of the true statement: 9 + recurse(8). Hopefully, you can see how the process repeats itself for n = 7, 6, 5, 4, 3, 2, 1 until the condition of n=1 is met.

Let us take a look at what is happening in the function towards the end, particularly when n=2 and n=1.

***FOR ILLUSTRATION PURPOSES ONLY. NOT ACTUAL SYNTAX***

When n=1, the function recurse(1) is ran once more. This time, n=1 satisfies the first condition in the if statements (1 == 1) so the computer will return the value of 1 and stops executing the function here. Remember, once a condition is satisfied in one of multiple if statements (starting from top down), the computer stops executing there.

Therefore, the final result of running the recurse function for n=10 is 55.

--

--

James Ng

Software engineer, math & physics educator, mentor