2.2 Programming Elements and Constructs Flashcards

1
Q

State what is meant by recursion.

A

Recursion involves a function that calls itself and each recursive call divides the problem into smaller subproblems until it reaches a base case which can be solved directly, then backtracks and solves the problem.

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

State one advantage and disadvantage of recursive implementations.

A

Advantage: Recursive implementations allow the task to be divided among many threads.

Disadvantage: Recursive implementations have higher overhead as each function call remains in the call stack until the base case is reached.

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

State 3 features of a successful recursive function.

A

A successful recursive function
1. calls itself
2. handles a base case withour further processing
3. each recursive call reduces the size of the problem and brings it closer to the base case.

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

Explain the use of a stack when a recursive function executes.

A

When a recursive function is called, its memory will allocated into a frame.

With each new function call, its frame will be pushed onto the call stack and control is passed to the new frame.

When the recursive function reaches its base case, its frame will be popped from the call stack and control is passed to the frame that is at the top of the call stack.

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

Describe an error that might be returned by a recursive function which calls itself too many times.

A

The recursive function might return a stack overflow error if the call stack runs out of memory and maximum recursion depth is exceeded.

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