Recursion

You know how to make methods, and you know how to call methods. (Your very first program did that! Ahhh, those simple days of one-line programs….) When you write methods, you’ll usually fill them with method calls. You can make methods, and they can call methods…see where I’m going with this? Yeah? No?

What if you wrote a method that called itself?

That’s recursion.

Well, on the surface, it’s an absurd idea; if all a method did was call itself, which would just call itself again, it would loop like that forever. (Although this is not technically a loop, it is similar; we can usually replace loops with recursion if we feel like it.) But of course, it could do other things as well and maybe call itself only some of the time.

Get Learn to Program, 2nd 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.