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 123 is substituted for the parameter n , and the body of
the method is executed. After the substitution of 123 for n , the code to be executed is
equivalent to
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.
Because 123 is not less than 10 , the else part is executed. However, the else part
begins with the method call
writeVertical(n / 10);
 
Search WWH ::




Custom Search