Java Reference
In-Depth Information
EXAMPLE:
(continued)
The task to be performed by
may be broken down into the following
writeVertical
two subtasks:
Simple Case:
If
, then write the number
to the screen.
n
<
10
n
After all, if the number is only one digit long, the task is trivial.
Recursive Case:
If
, then do two subtasks:
n
>= 10
1. Output all the digits except the last digit.
2. Output the last digit.
For example, if the argument were
, the first part would output
1234
1
2
3
and the second part would output
. This decomposition of tasks into subtasks can be
used to derive the method definition.
Subtask 1 is a smaller version of the original task, so we can implement this subtask
with a recursive call. Subtask 2 is just the simple case we listed above. Thus, an outline
of our algorithm for the method
4
with parameter
is given by the fol-
writeVertical
n
lowing pseudocode:
if (n < 10)
{
System.out.println(n);
}
else //n is two or more digits long:
{
writeVertical(
recursive subtask
the number
n
with the last digit removed
);
System.out.println(
the last digit of
n);
}
If you observe the following identities, it is easy to convert this pseudocode to a com-
plete Java method definition:
n/10
is the number
n
with the last digit removed.
n%10
is the last digit of
n
.
For example,
evaluates to
and
evaluates to
.
1234/10
123
1234%10
4
(continued)
Search WWH ::




Custom Search