Java Reference
In-Depth Information
We developed this call using our standard technique for developing function
calls; the only difference is that it is a call to the function being written —it is a
recursive call.
The final function is given in Fig. 15.2. And again, it consists of a base case
(the empty string), in which the answer is easy to calculate, and a recursive case.
The recursive case splits into two subcases; in each, the answer involves a recur-
sive call with a smaller part of the string as argument.
Because the body of the function is so simple, the two assertions could be
removed without harming readability. However, it is good to write such asser-
tions in all your recursive methods until you have fluency with recursion.
A function for a math definition
The notation n! is read as “ n factorial”. For n≥0 , n! is defined as the product of
the numbers in the range 1..n :
n!=1*2*3*... * n
By this definition, 0! is 1 because the product of 0 numbers is 1 . We can
write a recursive definition of n! by defining a base case and a recursive case:
See lesson
page 15.1 to
get the function
from the CD.
0! = 1
n!=n*(n-1)! ( for n>0)
It is easy to javanize this recursive definition of n! as a function. For the
base case, return 1 . For the recursive case, return n * (n - 1) , which can be done
with a recursive call, as shown in Fig. 15.3.
Many recursive math definitions can be easily javanized in this manner.
/** = p , with blank characters removed */
public static String deblank(String p) {
if (p.length() == 0)
{ return p; }
// { p has at least one character }
if (p.charAt(0) == ' ')
{ r eturn deblank(p.substring(1)); }
// { p 's first character is nonblank }
return p.charAt(0) + deblank(p.substring(1));
Figure 15.2:
Recursive function deblank
Search WWH ::

Custom Search