7.3. Summary

Recursion occurs whenever a routine calls itself, directly or indirectly, as part of its processing. One or more base cases are needed to end the recursion; otherwise, the algorithm loops indefinitely — a common problem to watch out for.

A recursive algorithm can always be recoded to use iteration in place of recursion by using a stack to maintain the algorithm's state, which is essentially what the program is doing anyway. Sometimes, however, an iterative alternative to a recursive algorithm can be found, and such solutions are generally more efficient than their recursive counterparts.

Get Programming Interviews Exposed: Secrets to Landing Your Next Job, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.