In computer programming, the term recursive describes a function or method that repeatedly calculates a smaller part of itself to arrive at the final result. It is similar to iteration, but instead of repeating a set of operations, a recursive function accomplishes repetition by referring to itself in its own definition. While the concept of recursive programming can be difficult to grasp initially, mastering it can be very useful. Recursion is one of the fundamental tools of computer science.
A classic example is the recursive method for computing the factorial of a number. The factorial of an integer n, which is written as n!, is the result of multiplying n by all the positive integers less than n. For instance, 3! = 3 x 2 x 1, which results in 6, and 4! = 4 x 3 x 2 x 1, which results in 24. An efficient way to calculate a factorial is with a recursive function.
Below is an example of a recursive factorial function written in JavaScript.
function factorial(n) { return (n === 0) ? 1 : n * factorial(n-1); }
As you can see, part of the definition of the function factorial is the result of factorial performed on a smaller integer. By calling itself, it can multiply the number by each positive number less than it and then return the final result. Recursive functions can be useful in other calculations, such as calculating Fibonacci numbers or the greatest common divisor.
Using recursive logic can have some downfalls, including the creation of an endless loop in programming. For this reason, having an escape condition (like a do until) helps reduce, if not eliminate, the chance of an endless loop from occurring. If an endless loop occurs, it can cause the program to use a lot of memory. Also, it could cause a program, operating system, or computer to stop functioning.
Escape, Function, Loop, Programming terms
Related information
- How to create a computer program.
- How to learn more about computers.
- Links to where to watch free online lectures and courses.
- See the programming terms for a full list of computer programming related terms.
- See our programming languages page for a list of all programming languages.
- All computer learning and training related pages.