Java Reference
In-Depth Information
EXAMPLE: (continued)
Translating this formula into Java says that the value returned by power(x, n)
should be the same as the value of the expression
power(x, n - 1)*x
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)
simply returns 1 (because 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. Because the
value of n is a legal value, the if-else statement is executed. Because 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. Because 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 suspended
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
(continued)
Search WWH ::




Custom Search