Task #1 Tracing Recursive Methods 1. Copy the file Recursion.java (see Code List
ID: 3912367 • Letter: T
Question
Task #1 Tracing Recursive Methods 1. Copy the file Recursion.java (see Code Listing 16.1) from the Student CD or as directed by your instructor. 2. Run the program to confirm that the generated answer is correct. Modify the factorial method in the following ways: a. Add these lines above the first if statement: int temp; System.out.println("Method call -- " + "calculating " + "Factorial of: " + n); Copyright © 2016 Pearson Education, Inc., Hoboken NJ b. Remove this line in the recursive section at the end of the method: return (factorial(n - 1) * n); c. Add these lines in the recursive section: temp = factorial(n - 1); System.out.println("Factorial of: " + (n - 1) + " is " + temp); return (temp * n); 3. Rerun the program and note how the recursive calls are built up on the run-time stack and then the values are calculated in reverse order as the run-time stack “unwinds”. Task #2 Writing Recursive and Iterative Versions of a Method 1. Copy the file Progression.java (see code listing 16.2) from the Student CD or as directed by your instructor. 2. You need to write class (static) methods for an iterative and a recursive version of each of the progressions. You will create the following methods: a. geometricRecursive b. geometricIterative c. harmonicRecursive d. harmonicIterative. Be sure to match these methods to the method calls in the main method. Code Listing 16.1 (Recursive.java) /** This program demonstrates factorials using recursion. */ public class Recursion { public static void main(String[] args) { int n = 7; // Test out the factorial System.out.println(n + " factorial equals "); System.out.println(Recursion.factorial(n)); System.out.println(); }
Explanation / Answer
The code will be
import java.util.concurrent.RecursiveAction;
public class factorial
{
public static int recursive(int n)
{
if(n==2)return 1;
if(n==1)return 1;
else
return recursive(n-1)+recursive(n-2);
}
public static int iterative(int n)
{
int f1=1;
int f2=1;
for(int i=2;i<n;i++)
{
int temp=f2;
f2+=f1;
f1=temp;
}
return f2;
}
public static void main(String[] arr)
{
System.out.println("Recursive");
System.out.println(recursive(4));
System.out.println(recursive(1));
System.out.println(recursive(2));
System.out.println(recursive(3));
System.out.println(recursive(5));
System.out.println("Iterative");
System.out.println(iterative(4));
System.out.println(iterative(1));
System.out.println(iterative(2));
System.out.println(iterative(3));
System.out.println(iterative(5));
}
}
The output is
Recursive
3
1
1
2
5
Iterative
3
1
1
2
5
Do give a thumbs up
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.