Recursion
Recursion
STRUCTURES
MAHESH GOYANI
MAHATMA GANDHI INSTITUE OF TECHNICAL EDUCATION & RESEARCH CENTER
[email protected]
RECURSION
How Recursion Works
Nothing special is required to handle a call to a
recursive method, whether the call to the method
is from outside the method or from within the
method.
At each call, the needed arguments are
provided, and the code is executed.
When the method completes, control returns to
the instruction following the call to the method.
How Recursion Works, cont.
Consider several methods m1, m2, …, mn, with
method m1 calling method m2, method m2 calling
method m3,…, calling method mn.
– When each method completes, control returns
to the instruction following the call to the
method.
In recursion, methods m1, m2, …, mn are all the
same method, but each call results in a distinct
execution of the method.
How Recursion Works, cont.
As always, method m1 cannot complete
execution until method m2 completes
execution, method m2 cannot complete
execution until method m3 completes
execution, …, until method mn completes
execution.
If method mn represents a stopping case, it
can complete execution, …, then method m2
can complete execution, then method m1 can
complete execution.
Recursion Guidelines
The definition of a recursive method typically
includes an if-else statement.
– One branch represents a base case which
can be solved directly (without recursion).
– Another branch includes a recursive call to
the method, but with a “simpler” or “smaller”
set of arguments.
Ultimately, a base case must be reached.
Infinite Recursion
If the recursive invocation inside the method
does not use a “simpler” or “smaller” parameter,
a base case may never be reached.
Such a method continues to call itself forever (or
at least until the resources of the computer are
exhausted as a consequence of stack overflow).
This is called infinite recursion.
Tracing recursive solution to factorial problem
Evaluating Exponents
Recursively