Java Reference
In-Depth Information
base exponent = base · base exponent - 1
and the terminating condition occurs when exponent is equal to 1 , because
base 1 = base
Incorporate this method into a program that enables the user to enter the base and exponent .
18.10 (Visualizing Recursion) It's interesting to watch recursion “in action.” Modify the factorial
method in Fig. 18.3 to print its local variable and recursive-call parameter. For each recursive call,
display the outputs on a separate line and add a level of indentation. Do your utmost to make the
outputs clear, interesting and meaningful. Your goal here is to design and implement an output for-
mat that makes it easier to understand recursion. You may want to add such display capabilities to
other recursion examples and exercises throughout the text.
18.11 (Greatest Common Divisor) The greatest common divisor of integers x and y is the largest
integer that evenly divides into both x and y . Write a recursive method gcd that returns the greatest
common divisor of x and y . The gcd of x and y is defined recursively as follows: If y is equal to 0 ,
then gcd(x, y ) is x ; otherwise, gcd(x, y ) is gcd(y, x % y ), where % is the remainder operator. Use
this method to replace the one you wrote in the application of Exercise 6.27.
18.12
What does the following program do?
1
// Exercise 18.12 Solution: MysteryClass.java
2
public class MysteryClass
3
{
4
public static int mystery( int [] array2, int size)
5
{
6
if (size == 1 )
7
return array2[ 0 ];
8
else
9
return array2[size - 1 ] + mystery(array2, size - 1 );
10
}
1 12
public static void main(String[] args)
13
{
14
int [] array = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 };
15
16
int result = mystery(array, array.length);
17
System.out.printf( "Result is: %d%n" , result);
18
} // end method main
19
} // end class MysteryClass
18.13
What does the following program do?
1
// Exercise 18.13 Solution: SomeClass.java
2
public class SomeClass
3
{
4
public static String someMethod( int [] array2, int x)
5
{
6
if (x < array2.length)
7
return String.format(
8
"%s%d " , someMethod(array2, x + 1 ), array2[x]);
9
else
10
return "" ;
11
}
12
 
Search WWH ::




Custom Search