Recursion Flashcards
What is recursion in programming?
A method that calls itself to solve a smaller instance of the same problem.
Write the base case for calculating factorial using recursion.
if (n == 0) return 1;
What is a stack overflow error in recursion?
It occurs when too many recursive calls exceed the stack’s capacity.
How do you calculate Fibonacci numbers recursively?
int fibonacci(int n) {
if (n <= 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
Why are base cases essential in recursion?
To prevent infinite recursion.
What is tail recursion?
A recursion where the recursive call is the last operation in the function.
How do you convert a recursive algorithm into an iterative one?
Use loops to simulate the recursive behavior.
What is a recursive tree?
A visual representation of function calls in recursion.
How does recursion differ from iteration?
Recursion uses function calls, while iteration uses loops.
What does the return statement do in recursion?
It passes the result back up the recursive call stack.