Nerd For Tech
Published in

Nerd For Tech


Recursion is a concept in computer programming that means defining a problem in terms of itself. Another way of explaining recursion is to define a function or calculate a number by the repeated use of an algorithm.

A good example of how to use recursion is if you are trying to calculate factorials.

The code above is how you can use recursion to calculate factorials. There are two returns in the function. The first is the base case. The base case is the case in which we know the answer with no need for a recursive call. The second return is the recursive case. The recursive case is the case in which we do not know the answer and a recursive call is needed.

To explain what is happening I will walk through the function.

Calling the function with three (Factorial(3)), the function will check if 3 equals one. It does not so it will continue down and return 3 * Factorial(3–1). This will call the function again with 2. Since 2 does not equal 1, the function will return 2 * Factorial(2–1). This calls the function using 1. Since 1 is equal to 1 the function will return 1. This will result in Factorial(3) returning 3 + 2 + 1 which equals 6 or 3!.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store