Java CW Recursive
Java CW Recursive
return 0;
else
1
2. What does the following statements display?
package javaapplication208;
int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
if ( size == 1 )
return array2[ 0 ];
else
1. (Recursive power Method ). Write a recursive method power (base, exponent) that,
when called, returns
Baseexponent
For example, power (3 ,4) = 3*3 *3 *3.Assume that exponent is an integer greater than or equal
to 1.
Case 1: when exponent is even number
Case 2: when the exponent is odd number
Incorporate this method into a program that enables the user to enter base and exponent.
2
// program 1
package javaapplication237;
public class JavaApplication237 {
public static void main(String[] args) {
for ( int counter = 0; counter <= 10; counter++ )
System.out.printf( "%d! = %d\n", counter, factorial( counter ) );
}
public static long factorial( long number ) {
if ( number <= 1 ) // test for base case
return 1; // base cases: 0! = 1 and 1! = 1
else // recursion step
return number * factorial( number - 1 );
} // end method factorial
run:
0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800
BUILD SUCCESSFUL (total time: 0 seconds)
3
3.(Visualizing Recursion) It’s interesting to watch recursion ‘in action”. Modify the factorial method
in program 1. 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. Your goal here is to design and
implement an output format that makes it easier to understand recursion.
run:
Step 1: 1
0! = 1
Step 1: 1
1! = 1
Step 1: 2 * factorial( 1 )
Step 2: 1
2! = 2
Step 1: 3 * factorial( 2 )
Step 2: 2 * factorial( 1 )
Step 3: 1
3! = 6
Step 1: 4 * factorial( 3 )
Step 2: 3 * factorial( 2 )
Step 3: 2 * factorial( 1 )
Step 4: 1
4! = 24
4
4.(Recursive Binary Search) Write a recursive RecursiveBinarySearch method to
perform a binary search of the array. The method should receive the search key, starting index
and ending index as arguments. If the search key is found, return its index in the array. If the
search key is not found, prints search key was not found. Also write a program to test your
method.
234,289,296,310,319,388,394,
417,429,447,521,536,600 };
run: