In java language Part 1 For the next two questions, use the following recursive
ID: 3697769 • Letter: I
Question
In java language
Part 1
For the next two questions, use the following recursive method:
public int secretMethod(int x, int y) {
if (x == y)
return 0;
else
return secretMethod(x-1, y) + 1;
}
Question 1
If the method is invoked as secretMethod(9, 3), what is returned?
Answer:
Question 2
Calling this method will result in infinite recursion if which condition below is initially true?
Select one:
a. (x > y)
b. (x = = 0 && y != 0)
c. (x < y)
d. (x = = y)
e. (x != y)
Part 2
For the next four questions, refer to the following recursive factorial method.
public int factorial(int x) {
if (x > 1)
return x * factorial (x – 1);
else
return 1;
}
Question 3
What is returned if factorial(3) is called?
Answer:
Question 4
What is returned if factorial(0) is called?
Select one:
a.0
b. 1
c. 2
d. nothing, factorial(0) causes infinite recursion
e. nothing, factorial(0) produces a run-time error
Question 5
How many times is the factorial method invoked if originally called with factorial(5)? Include the original method call in your counting.
Answer:
Question 6
What condition defines the base case for this method?
Select one:
a. (x <= 1)
b. (x > 1)
c. (x <= 0)
d. (x = = 0)
e. (x = = 1)
Part 3
For the next four questions, assume that int[ ] a = {3, 5, 2, 4, 7, 3, 4, 5, 3} and consider the two recursive methods below foo and bar.
public int foo(int[ ] a, int b, int j) {
if (j < a.length)
if (a[j] != b)
return foo (a, b, j+1);
else
return foo (a, b, j+1) + 1;
else
return 0;
}
public int bar(int[ ] a, int j) {
if (j < a.length)
return a[j] + bar(a, j+1);
else
return 0;
}
Question 7
What is the result of calling foo(a, 3, 0);?
Answer:
Question 8
What is the result of calling foo(a, 3, 4);?
Answer:
Question 9
What is the result of calling bar(a, 5);?
Answer:
Question 10
What is the result of calling bar(a, 9);?
Answer:
Question 11
Write a recursive method to print every other element in an array, starting with the element in position 0.
The method header is: public void printEveryOther(int[] nums)
Explanation / Answer
1- 6
2- c
3- 6
4- b
5- 6
6- a
7- 3
8- 2
9- 15
10- 0
11-
public void printEveryOther(int[] nums)
{
if(i*2<nums.length)
{
System.out.println(nums[i*2]);
i++;
printEveryOther(nums);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.