Unit 8: Recursion Flashcards

1
Q

What is recursion in programming?

A

A technique where a method calls itself to solve a smaller version of the same problem.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is the recursive solution to “how many people are behind me in a column”?

A

Ask the person behind you how many are behind them. If none, return 0; else, return their answer + 1.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What are the two essential components of any recursive algorithm?

A

Base case – a simple condition that stops the recursion.
Recursive case – breaks the problem into smaller subproblems.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Why is recursion useful?

A

Provides elegant, simple solutions

Can solve problems better than iteration

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What does getArea(4) return using recursion?

A

getArea(1) → 1

getArea(2) → 1 + 2 = 3

getArea(3) → 3 + 3 = 6

getArea(4) → 6 + 4 = 10

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is the recursive formula for Fibonacci numbers?

A

public static long fib(int n) {
if (n <= 2) return 1;
else return fib(n - 1) + fib(n - 2);
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Why is the recursive Fibonacci function inefficient?

A

it recalculates the same values multiple times (e.g., fib(3) is called 3 times in fib(6)).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What are the main differences between loops and recursion?

A

Loops use repetition explicitly

Recursion uses repeated method calls

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What happens in memory during recursion?

A

Each call gets its own local variables and parameters. Memory is freed when the method returns.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is infinite recursion and why is it bad?

A

It’s when no base case is met, leading to endless method calls and eventual stack overflow.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

When should recursion be avoided?

A

When performance is critical or the problem is easily solved iteratively.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly