Lesson 1 · Unit 01
The base case
Every recursion needs a way to stop
What you practise
- Countdown and sum to n
- A missing base case overflows the stack
Try a question from this lesson
Pick one
This function calls itself. What does it print, top to bottom?
def countdown(n):
if n == 0:
print("go")
return
print(n)
countdown(n - 1)
countdown(3)function countdown(n) {
if (n === 0) {
console.log("go");
return;
}
console.log(n);
countdown(n - 1);
}
countdown(3);function countdown(n: number): void {
if (n === 0) {
console.log("go");
return;
}
console.log(n);
countdown(n - 1);
}
countdown(3);Correct answer
3 2 1 go
Why
Each call prints its n and hands n - 1 to a fresh call. The call with n = 0 prints "go" and returns without calling again. A 0 is never printed because the check comes before the print.
TypeScript note: void is the return type of a function that returns nothing useful.
The idea
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Two parts, always
A recursive function has a base case and a recursive case.
The base case answers the smallest input directly. The recursive case does one small step and calls itself on a smaller input, so every call moves closer to the base case.
def total(n):
if n == 0: # base case
return 0
return n + total(n - 1)function total(n) {
if (n === 0) return 0; // base case
return n + total(n - 1);
}function total(n: number): number {
if (n === 0) return 0; // base case
return n + total(n - 1);
}TypeScript noteA recursive function needs its return type written out (: number). TypeScript cannot infer a type that depends on the function itself.
9 more exercises in the app
- 2× type the answer
- 3× multiple choice
- 1× fill the blanks
- 1× true or false
- 1× match the pairs
- 1× order the lines
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.