A) Consider the following code: public static void test_a(int n) { System.out.pr
ID: 3560068 • Letter: A
Question
A) Consider the following code: public static void test_a(int n) { System.out.println(n + " "); if (n>0) test_a(n-2); } What is printed by the call test_a(6)?
B) Consider the following code: public static void test_b(int n) { if (n>0) test_b(n-2); System.out.println(n + " "); } What is printed by the call test_b(6)?
C) When the compiler compiles your program, how is a recursive call treated differently than a non-recursive method call?
D) What property of fractals lends itself to recursive thinking?
E) Write a method that uses a loop to figure out the factorial (n!). The method will take an integer n and return the value of n! (return answer, dont print)
F) Take the method above and convert it to a recursive method.
G) Compare the two methods (#5 and #6 above) and answer the following: a. What is the stopping case for each (what causes the methods to end)? b. How do you guarantee that the methods will stop (infinite loop, infinite recursion)? c. Which method one is better? Why?
H) Write an iterative method that calculates the SUM of all integers between 1 and a given integer N (input into the method). Write a corresponding recursive solution. (return answer, dont print)
**EXTRA CREDIT ** Looking at your solution(s) in #8 above its easy to see that as n gets larger, the solution is takes longer to solve (or increases the chance of overflow). Is this the best we can do? (is this the most efficient solution)? If so, explain why. If not, give your solution (and make sure you explain why it is more efficient).
Explanation / Answer
A)6 4 2
B)2 4 6
C)Recursive call is kept on a stack;
D)A fractal is a geometric shape that can be made up of the same
pattern repeated at different scales and orientations. The
nature of a fractal lends itself to a recursive definition.
E)int i , p =1;
for(i=1;i<=n;i++)
p = p*i
F)int rec(int r)
{
if(r==0)
return 1;
else
return r*(rec(r-1);
}
G) a. Stooping case for 5 is the loop variable and for case 6 is if condition. Case 2 is better as recursion fast.
H)for(i=1;i<=n;i++)
{
sum+=i;
}
int sum(int s)
{
if(s==0)
return 0;
else
return s+sum(s-1);
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.