0% found this document useful (0 votes)
14 views5 pages

Java Recursion Examples and Exercises

The document contains 4 questions related to recursion in Java: 1) Write a recursive power method to calculate base^exponent. It handles even and odd exponents separately. 2) Write a recursive factorial method and test it by calculating 0! to 10!. 3) Modify the factorial method to print the recursion steps for readability. 4) Write a recursive binary search method to search an array and return the index if found, else print not found. Test it by searching values in a sample array.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views5 pages

Java Recursion Examples and Exercises

The document contains 4 questions related to recursion in Java: 1) Write a recursive power method to calculate base^exponent. It handles even and odd exponents separately. 2) Write a recursive factorial method and test it by calculating 0! to 10!. 3) Modify the factorial method to print the recursion steps for readability. 4) Write a recursive binary search method to search an array and return the index if found, else print not found. Test it by searching values in a sample array.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Class Work:

1. Show the output of the following program:

public class RangeSum {

public static void main(String[] args)

int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9};

[Link]("The sum of elements 2 through " +

"5 is "+ rangeSum(numbers, 2, 5));

public static int rangeSum(int[] array, int start, int end)

if (start > end)

return 0;

else

return array[start] + rangeSum(array, start + 1, end);

1
2. What does the following statements display?

package javaapplication208;

public class JavaApplication208 {

public static void main(String[] args) {

int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

int result = mystery( array, [Link] );

[Link]( "Result is: %d\n", result );

public static int mystery( int[] array2, int size )

if ( size == 1 )

return array2[ 0 ];

else

return array2[ size - 1 ] + mystery( array2, size - 1 );

} // end method mystery

1. (Recursive power Method ). Write a recursive method power (base, exponent) that,
when called, returns
Baseexponent
For example, power (3 ,4) = 3*3 *3 *[Link] 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++ )
[Link]( "%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

BUILD SUCCESSFUL (total time: 3 seconds)

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.

Array elements : {101,142,147,189,199,207,222,

234,289,296,310,319,388,394,

417,429,447,521,536,600 };

run:

Enter a value to search for :189

189 was found at element 3

Do you want to search again? ( Y or N): Y

Enter a value to search for :600

600 was found at element 19

Do you want to search again? ( Y or N): Y

Enter a value to search for :1

1 was not found

Do you want to search again? ( Y or N): N

Common questions

Powered by AI

A recursive factorial implementation involves a function that calls itself with decremented values until the base case is reached, using stack memory for each call. In contrast, an iterative implementation uses loops to accumulate the product in a running total, which often leads to lower memory overhead and potentially faster execution. Iteration avoids the function call overhead and stack depth limitations present in recursion, making it more efficient in terms of memory for large numbers.

The 'rangeSum' method uses recursion by defining a base case where if 'start' exceeds 'end', the result is 0, which stops further recursive calls. Otherwise, it adds the element at the 'start' index to the result of 'rangeSum' called with 'start+1'. For the array {1, 2, 3, 4, 5, 6, 7, 8, 9}, the method sums elements from index 2 (value 3) to index 5 (value 6), resulting in 3 + 4 + 5 + 6 = 18. Therefore, the output is "The sum of elements 2 through 5 is 18."

Using recursion to visualize problem-solving is effective because it exposes the recursive call structure and parameter changes at each stage, aiding in conceptualizing recursion flows. It helps in debugging by illustrating recursive depth and sequence clearly. However, for deeply recursive structures or large datasets, output can become unwieldy and less comprehensible, thus limiting practicality past certain complexity levels.

Modifying the 'factorial' method to print its local variables and recursive-call parameters enhances understanding by making the flow of recursion more transparent. It allows observation of each recursive step, displaying how values change and accumulate, providing insights into how recursion unfolds one step at a time while emphasizing the base case and recursive progression.

The main drawbacks of using recursion for factorial calculation include increased memory usage due to the stack space required for each recursive call. Large inputs can result in stack overflow errors. Additionally, recursion can be less computationally efficient than iterative solutions due to the overhead of repeatedly calling functions and managing stack operations, which iterative loops do not require.

Recursive binary search is efficient for sorted arrays, as it reduces the search space logarithmically by halving it each iteration, which minimizes the time complexity to O(log n). Limitations include the risk of stack overflow with large input sizes due to deep recursion levels. Iterative implementations avoid these memory concerns and might be preferred in contexts where tail recursion optimization isn't available.

The 'factorial' method performs well on small inputs due to simple base cases and minimal recursive depth, leading to minimal stack usage and faster computation. For large inputs, however, the depth of recursion increases significantly, leading to higher memory usage and a potential for stack overflow. Each recursive call introduces overhead, impacting performance negatively as input size grows.

The 'mystery' method calculates the sum of array elements using recursion by checking if the 'size' is 1, where it returns the first element, effectively the base case. Otherwise, it adds the last element (array[size - 1]) to the result of calling 'mystery' with 'size - 1', which is the recursive step. This accumulates the sum backward through the array, collecting and summing each element.

Implementing the 'RecursiveBinarySearch' method to search for 310 in the provided array would result in finding the element at index 10. The recursion narrows down the search range effectively by comparing the middle element of the current range with the search key and adjusting the indexes appropriately, leading to efficient identification of 310 at the specified index.

For even exponents, the method can optimize calculations by using the identity (base^(exponent/2))^2, effectively halving the depth of recursion. For odd exponents, the method needs an additional multiplication of the base once the exponent is reduced to an even number. For example, power(3, 4) would lead to (3^(2))^2 = 9^2 = 81, while power(3, 5) would be 3 * power(3, 4) = 3 * 81 = 243. This illustrates the differentiation in handing recursion depth and computational efficiency based on exponent parity.

You might also like