Java Reference
In-Depth Information
EXAMPLE: (continued)
The definition of the method power given in Display 11.3 does return this value for
power(x, n) , provided n > 0 .
The case where n is equal to 0 is the stopping case. If n is 0 , then power(x, n) sim-
ply returns 1 (since x 0 is 1 ).
Let's see what happens when the method power is called with some sample values.
First consider the simple expression:
power(2, 0)
When the method is called, the value of x is set equal to 2 , the value of n is set equal to
0 , and the code in the body of the method definition is executed. Since the value of n is
a legal value, the if-else statement is executed. Since this value of n is not greater
than 0 , the return statement after the else is used, so the method call returns 1 . Thus,
the following would set the value of result3 equal to 1 :
int result3 = power(2, 0);
Now let's look at an example that involves a recursive call. Consider the expression
power(2, 1)
When the method is called, the value of x is set equal to 2 , the value of n is set equal
to 1 , and the code in the body of the method definition is executed. Since this value
of n is greater than 0 , the following return statement is used to determine the value
returned:
return ( power(x, n 1)*x );
which in this case is equivalent to
return ( power(2, 0)*2 );
At this point, the computation of power(2, 1) is suspended, a copy of this sus-
pended computation is placed on the stack, and the computer then starts a new
method call to compute the value of power(2, 0) . As you have already seen, the
value of power(2, 0) is 1 . After determining the value of power(2, 0) , the computer
replaces the expression power(2, 0) with its value of 1 and resumes the suspended
computation. The resumed computation determines the final value for power(2, 1)
from the above return statement as
power(2, 0)*2 is 1*2 which is 2
(continued)
Search WWH ::




Custom Search