Quiz 8 Recursion
Use the following recursive method.public int question(int x, int y){if (x == y) return 0;else return question(x-1, y) + 1;} If the method is called as question(8, 3), what is returned?
5. The method computes x - y if x > y. The method works as follows: each time the method is called recursively, it subtracts 1 from x until (x == y) is becomes true, and adds 1 to the return value. So, 1 is added each time the method is called, and the method is called once for each int value between x and y.
Which of the following will result from infinite recursion in Java?
The program will run out of memory
In a recursive solution, -------- is (are) always necessary
a base case
The towers of hanoi puzzle cannot be solved iteratively
false
------------- recursion results from the lack of a base case
infinite
Which of the following statements is true
solutions that are easily expressed recursively.
Use the following recursive method. public int question(int x, int y){ if (x == y){ return 0; } else{ return question(x-1,y) +1;} } Calling this method will result in infinite recursion if which condition below is initially true?
(x < y) If (x < y) is true initially, then these clause is executed resulting in the method being recursively invoked with a value of x - 1, or a smaller value of x, so that (x < y) will be true again, and so for each successive recursive call, (x < y) will be true and the base case, x == y, will never be true.
Refer to the following recursive factorial method.public int factorial(int x) { if (x > 1) return x * factorial (x - 1); else return 1; }What is returned if factorial(3) is called?
6.With factorial(3), x > 1, so it returns 3 * factorial(2), with factorial(2), x > 1 so it returns 2 * factorial(1), with factorial(1), 1 is returned, so we have 3 * 2 * 1 = 6.
What does the following method compute? Assume the method is called initially with i = 0 public int question(String a, char b, int i){ if (i == a.length( )) return 0; else if (b == a.charAt(i)) return question(a, b, i+1) + 1; else return question(a, b, i+1); }
The number of times char b appears in String a. The method compares each character in String a with char b until i reaches the length of String a. 1 is added to the return value for each match.
What is wrong with the following recursive sum method? The method is supposed to sum up the values between 1 and x (for instance, sum(5) should be 5 + 4 + 3 + 2 + 1 = 15).public int sum(int x){ if (x = = 0) return 0; else return sum(x - 1) + x;}
the base case condition should be (x<= 0 ) instead of (x==0). The method does not appropriately handle a negative parameter, such as sum(-5). The result is infinite recursion. We might define a negative parameter as something that should return 0, or allow a negative parameter to compute a negative sum as in:public int sum(int x){ if (x = = 0) return 0; else if (x < 0) return -1 * sum(-x); else return sum(x - 1) + x;}