80 likes | 173 Views
Recursion. CSC 202. 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.
E N D
Recursion CSC 202
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.
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.
“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.
“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.
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.
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".
Recursion versus Iteration • Iteration is more efficient, in general. • Recursion may be easier to code and understand.