The base case tells a recursive function when to stop. Otherwise it would keep calling itself forever!
For example, we could add all numbers 1 to n recursively like this:
If we input 3 as our n, this function will take 3, then add 2, then add 1, then add 0, then add -1, then add -2, etc forever (or until the program crashes).
We want to stop adding when n gets to 1. We'd say that our "base case" is n <= 1, and our code might look like:
Whenever writing a recursive function, be careful not to forget the base case!
Interview coming up?
Get the free 7-day email crash course. You'll learn how to think algorithmically, so you can break down tricky coding interview questions.
No prior computer science training necessary—we'll get you up to speed quickly, skipping all the overly academic stuff.
No spam. One-click unsubscribe whenever.
You're in! Head over to your email inbox right now to read day one!