Presentation is loading. Please wait.

Presentation is loading. Please wait.

Recursion CSC 202.

Similar presentations


Presentation on theme: "Recursion CSC 202."— Presentation transcript:

1 Recursion CSC 202

2 Understanding Recursion
Recursion occurs when a method calls itself. In reality, the method calls a “fresh copy” of itself. By “fresh copy” we mean a copy whose attributes are in the original state. A recursive method typically solves a small part of the problem and calls itself to solve the remaining part of the problem.

3 Making Recursion Work In order for recursion to work successfully, it must eventually terminate – just like a loop. Generally, a recursive routine should test for reaching the termination condition before activating another copy of itself. When another copy of the recursive routine is activated, the activating routine waits for the new copy to return a result.

4 “Unwinding” Recursion
Thus, many copies may be waiting for the termination condition to be reached. When a recursive routine reaches the point that the problem has been reduced so that a solution is at hand, the solution is returned to the caller. The caller (the copy that called the routine that finally found a solution) uses the returned result to create a solution that, in turn, is returned to its caller.

5 “Unwinding” Recursion
This continues as each routine returns a result and is removed from the stack, until the first copy (that started the succession of recursive calls) receives a result that it presents.

6 Recursive Methods Recursion
A recursive method is designed to solve the simplest case of a particular problem, called the base case. Given a more complex case of the problem, a recursive method typically states the solution partly in terms of solution of a simpler case; this continues until the base case is reached. If never reached, an infinite recursion occurs.

7 Humorous Definitions of Recursion
"If you already know what recursion is, just remember the answer. Otherwise, find someone who is standing closer to someone who knows what recursion is than you are; then ask him or her what recursion is.“ Definition: Recursion - If you still don't get it, see: "Recursion".

8 Recursion versus Iteration
Iteration is more efficient, in general. Recursion may be easier to code and understand.


Download ppt "Recursion CSC 202."

Similar presentations


Ads by Google