A recursive call in programming repeats a subroutine or function until a base case is met. It is similar to a loop and can be more efficient. A roofer applying shingles is an example of recursion.
In programming, a recursive call is a command within a subroutine or function that tells the program to run the same subroutine again. The repetition of execution can be the direct result of the function, or a second function can be triggered which, in turn, references the first function. A recursive call has some similarities to the dreaded infinite loop, but the subroutine always has a conditional statement that tells the program when to stop repeating the recursion.
The concept of recursion is perhaps best illustrated through the use of an example. Let’s say a roofer is applying new shingles to a house. To begin, she has to carry a bundle of tiles to the roof. Once she has nailed the first beam, she must go down the ladder, retrieve another beam and nail it in place. The process continues as a series of “go, get, come back” until the last tile is applied. At that point, the roofer is free to move on to the next job or go home.
While the example is an oversimplification, it contains all the elements of a recursive call. There is a starting point, the roofer has to retrieve what he needs, go back to the beginning and, when the final condition is satisfied, stop. This is basically what the program does; starts, implements an action, returns to itself and ends when the end condition is met.
The final condition is called the base case. It is essential for all recursive calls; without it, the function would keep repeating. At best, this results in draining system memory resources. Normally the overload will cause the program to crash at some point, but by the time the problem is discovered, significant damage can be done.
Experienced programmers might recognize the similarity between a recursive call and a “for” or “while” loop. For example, if the goal is to find the total inventory count of all inventory with part numbers greater than 999, a “for” loop tells the program to locate all qualifying instances, and a “while” loop tells the program to loop only as long as the indicated condition is valid. A recursive call could be said to combine some of the characteristics of these loops with an “if-then-else” statement; if this condition is true, then do this, or do something different if the condition is false. However, recursion generally allows for more compact code and allows you to pass the problem to the function closer to where it’s needed.
Protect your devices with Threat Protection by NordVPN