Java Reference
In-Depth Information
However, the process will not terminate unless eventually one of the recursive calls
does not depend on recursion to return a value. The general outline of a successful
recursive method definition is as follows:
One or more cases in which the method accomplishes its task by using recursive
call(s) to accomplish one or more smaller versions of the task.
One or more cases in which the method accomplishes its task without the use of
any recursive calls. These cases without any recursive calls are called base cases or
stopping cases .
Often an if-else statement determines which of the cases will be executed. A
typical scenario is for the original method call to execute a case that includes a recur-
sive call. That recursive call may in turn execute a case that requires another recur-
sive call. For some number of times, each recursive call produces another recursive
call, but eventually one of the stopping cases should apply. Every call of the method
must eventually lead to a stopping case, or else the method call will never end because of
an infinite chain of recursive calls. (In practice, a call that includes an infinite chain
of recursive calls will usually terminate abnormally rather than actually running
forever.)
The most common way to ensure that a stopping case is eventually reached is to
write the method so that some (positive) numeric quantity is decreased on each
recursive call and to provide a stopping case for some “small” value. This is how we
designed the method writeVertical in Display 11.1. When the method write-
Vertical is called, that call produces a recursive call with a smaller argument. This
continues with each recursive call producing another recursive call until the argument
is less than 10 . When the argument is less than 10 , the method call ends without pro-
ducing any more recursive calls and the process works its way back to the original call
and the process ends.
base case
stopping
case
General Form of a Recursive Method Definition
The general outline of a successful recursive method definition is as follows:
One or more cases that include one or more recursive calls to the method being
defined. These recursive calls should solve “smaller” versions of the task per-
formed by the method being defined.
One or more cases that include no recursive calls. These cases without any recur-
sive calls are called base cases or stopping cases .
Search WWH ::




Custom Search