Java Reference
In-Depth Information
Discussion of the recursive pattern
The body of the method consists of two cases:
The base case consists of parameter values in which the task to be done
can be carried out simply, with no recursive calls. Segment b[h..h-1] is
empty —there are no elements to set to 0 . The body simply returns.
The recursive case consists of parameter values for which a recursive call
is made. One step is made —set one array element to 0 . Then a recursive
call is made to perform the rest of the task.
The recursive call was developed using the technique for developing method
calls taught in Sec. 2.2.2. The only difference is that the call is on the method in
which the call occurs.
Comments on the code in Fig. 15.1
The procedure body of Fig. 15.1 is so short and simple that the comments
are not needed, so we eliminate them:
/** Set elements of b[h..k] to 0 */
public static void setToZero( int [] b, int h, int k) {
if (h == k + 1)
{ return ; }
b[h]= 0;
setToZero(b, h + 1, k);
}
We can write this method body so that a return statement is not needed:
if (h <= k) {
b[h]= 0;
setToZero(b, h + 1, k);
}
However, we prefer the original body. It handles the base case first, returning as
soon as it is handled. The rest of the body need not deal with it. We generally
write recursive methods in the form used in Fig. 15.1.
/** Set elements of b[h..k] to 0. Precondition: h<=k+1*/
public static void setToZero( int [] b, int h, int k) {
if (h == k + 1)
{ return ; }
// { b[h..k] is nonempty }
b[h]= 0;
setToZero(b, h + 1, k);
}
Figure 15.1:
Recursive procedure setToZero
Search WWH ::




Custom Search