Skip to main content

Chapter 21 Recursive functions

Up to this point, weโ€™ve been using while and for loops whenever weโ€™ve needed to repeat something. functions that use iteration are called iterative. They are a straight-forward way to repeat some code, but they are not the only way.
In this chapter, we explore one of the most magical things that a function can do: invoke itself to solve a smaller version of the same problem. A function that invokes itself is called recursive. Recursive functions are another way to repeat code, and they can lead to elegant solutions for some complex problems.
In addition to being a way to simply and clearly express some algorithms, there are entire classes of programming languages that rely almost exclusively on recursion instead of iteration. For example, in functional programming languages, variables canโ€™t be assigned new values. This makes it impossible to write something like a traditional counting loop. So in these languages, recursion is the primary method for performing repetitive tasks.