Java Reference
In-Depth Information
EXAMPLE:
(continued)
The following is the complete code for the method:
public static void writeVertical( int n)
{
if (n < 10)
{
System.out.println(n);
}
else //n is two or more digits long:
{
writeVertical(n/10);
System.out.println(n%10);
}
}
Tracing a Recursive Call
Let's see exactly what happens when the following method call is made (as in Display 11.1):
writeVertical(123);
When this method call is executed, the computer proceeds just as it would with any method
call. The argument
is substituted for the parameter
and the body of the method is exe-
123
n
cuted. After the substitution of
for
, the code to be executed is equivalent to
123
n
if (123 < 10)
{
System.out.println(123);
}
else //n is two or more digits long:
{
writeVertical(123/10);
System.out.println(123%10);
}
Computation will stop here
until the recursive call
returns.
Since
is not less than
, the
part is executed. However, the
part begins
123
10
else
else
with the method call
writeVertical(n/10);
Search WWH ::




Custom Search