One of the most important concepts that you’ll need to understand in programming is recursion. Simply put, recursion is when a function calls itself. Using a recursive algorithm is something you are guaranteed to learn about during your studies as a programmer so I thought I’d take some time to write a post about it.
First off, you will need a base case so that the function doesn’t potentially get caught in an infinite loop causing stack overflow. A stack overflow is an undesirable condition in which a particular computer program tries to use more memory space than the call stack has available. In programming, the call stack is a buffer that stores requests that need to be handled. In computer science, a call stack is a stack data structure that stores information about the active subroutines of a computer program.
A Recursive Function
The following is an example of a function designed to count the number of vowels in a given string using recursion. It checks to see if the string is empty as the base case and returns 0 if so. Then, it checks for vowels letter by letter as the function calls itself.
Recursion is important to understand for any programmer. It isn’t always practical or the best solution but it’s essential to grasp nonetheless. It will often come up during technical interviews and it can also help you visualize a solution when writing code to solve certain problems.