The base case tells a recursive method 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 method 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 method, be careful not to forget the base case!
Base Case interview questions to practice
Each one walks you through a real coding interview problem one hint at a time.
- Recursive String Permutations » Write a recursive function of generating all permutations of an input string.
- Compute the nth Fibonacci Number » Computer the nth Fibonacci number. Careful--the recursion can quickly spin out of control!
Your first 3 questions are free. Just sign in, no credit card.
See also:
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!
Interview Cake