Answer the questions using the Java code below: public static int rabbit(int n)
ID: 3831107 • Letter: A
Question
Answer the questions using the Java code below:
public static int rabbit(int n) // line 1
{ // line 2
if (n <= 2) // line 3
return 1; // line 4
else // n > 2, so n - 1 > 0 and n - 2 > 0 // line 5
return rabbit(n - 1) + rabbit(n - 2); // line 6
} // end rabbit
Which of the above expressions indicates the "base case"?
Which of the above has recursive calls?
How would you describe what the above method returns?
Study the code below. What does that method do?
Is the rabbit method shown above a good use of recursion or a bad use of recursion? Why or why not? (MORE OF THE EXERCISE BELOW THE FOLLOWING method)
After completing the instructions below, what was the last "call #"? What does that number indicate?
public static int exercise5(int n)
{
int previous = 1;
int current = 1;
int next = 1;
for (int i = 3; i <= n; i++)
{
next = current + previous; // exercise5(i)
previous = current; // Get ready for next iteration
current = next;
} // end for
return next;
} // end exercise5
Now add a static class variable to be declared:
public static int numCalls; // DECLARE OUTSIDE THE METHOD INSIDE THE CLASS
and change the rabbit method to add the following statements between lines 2 and 3 using:
++numCalls;
System.out.println( "n = " + n + " for call # " + numCalls );
Then write main so it does the following:
call rabbit(10), assign the return value to a main int, and display the result.
call exercise5(10), and display the result with a label "Result of calling exercise5(10)".
Explanation / Answer
public static int rabbit(int n) // line 1
{ // line 2
if (n <= 2) // line 3
return 1; // line 4
else // n > 2, so n - 1 > 0 and n - 2 > 0 // line 5
return rabbit(n - 1) + rabbit(n - 2); // line 6
} // end rabbit
Which of the above expressions indicates the "base case"?
line3, and 4 are the base cases.
Which of the above has recursive calls?
line6 represents the recursive call.
How would you describe what the above method returns?
Its a program for fibonacci series. Everytime its the sum of the 2 previous terms,
if n is greater than 2.
Study the code below. What does that method do?
Its the fibonacci series method.
Is the rabbit method shown above a good use of recursion or a bad use of recursion?
Why or why not? (MORE OF THE EXERCISE BELOW THE FOLLOWING method)
Its a bad use. The reason is because the almost same method is being called
twice which almost doubled the complexity of the code.
After completing the instructions below, what was the last "call #"?
What does that number indicate?
Its a fibonacci number.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.