Recursion is when a function calls itself to solve smaller parts of a problem until it reaches a simple case it can solve directly.
Click to reveal answer
beginner
What is a base case in recursion?
A base case is the simplest situation in a recursive function where the function stops calling itself and returns a result directly.
Click to reveal answer
intermediate
How does the call stack help in recursion?
The call stack keeps track of all the active function calls. Each recursive call adds a new layer to the stack until the base case is reached, then the stack unwinds as results return.
Click to reveal answer
beginner
Consider this code snippet:
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
What happens when factorial(3) is called?
factorial(3) calls factorial(2), which calls factorial(1). factorial(1) returns 1 (base case). Then factorial(2) returns 2 * 1 = 2, and factorial(3) returns 3 * 2 = 6.
Click to reveal answer
beginner
Why is it important to have a base case in recursion?
Without a base case, the function would call itself forever, causing the program to crash or run out of memory.
Click to reveal answer
What does a recursive function always need to stop calling itself?
AA variable
BA loop
CA base case
DAn error
✗ Incorrect
A base case tells the recursive function when to stop calling itself.
In recursion, what does the call stack do?
AStores all active function calls
BDeletes old functions
CRuns functions in parallel
DPrevents recursion
✗ Incorrect
The call stack keeps track of all active function calls, including recursive ones.
What will factorial(1) return in a typical factorial recursive function?
A0
BError
Cn
D1
✗ Incorrect
factorial(1) returns 1 as the base case.
What happens if a recursive function has no base case?
AIt returns 0
BIt runs forever until error
CIt stops immediately
DIt runs once
✗ Incorrect
Without a base case, recursion never stops and causes a crash.
Which of these is a real-life example of recursion?