Recursion Tracing:
For each problem, trace the code segment and identify the output of the code.
Problem 1
public static int mystery(int x) {
if (x == 2) {
return 2;
}
else {
return x * mystery(x - 2);
}
}
What is the base case?
When x == 2
What is the recursive call?
Recursive call: x*mystery(x-2)
Trace the code segment in the space below to determine the output of the call mystery(10).
Returned value Int x
80 10
48 8
24 6
8 4
2 2
Problem 2
public static int division(int y) {
if (y <= 0) {
return 1;
}
else {
return y / division(y - 3);
}
}
What is the base case?
When y <=0 (y is smaller than or equal to zero)
What is the recursive call?
Retun y/division(y-3)
Trace the code segment in the space below to determine the output of the call division(14).
Returned value Int y
1 14
1 11
1 8
2 5
-2 2
1 -1
Practice tracing recursive methods.
Problem 3
public static int sumNumbers(int[] numbers, int numbersLength) {
if (numbersLength <= 0) {
return 0;
}
return (sumNumbers(numbers, numbersLength - 1) +
numbers[numbersLength - 1]);
}
Call from main()
int[] numbers = {21, 2, 4, 82, 81, 33, 67, 52, 22, 23};
int sum = sumNumbers(numbers, numbers.length);
System.out.println("Sum: " + sum);
What is the base case?
When int numberslength <= 0 (numberslength is smaller than or equal to 0)
What is the recursive case?
Trace the code segment in the space below to determine the output of RecursionRunner.
Problem 4
public static int getListLength(ArrayList<Integer> list, int start) {
if (start == list.size()) {
return 0;
}
return 1 + getListLength(list, start + 1);
}
Call from main:
ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(25);
numbers.add(32);
numbers.add(41);
numbers.add(28);
numbers.add(21);
numbers.add(45);
numbers.add(36);
numbers.add(19);
numbers.add(27);
numbers.add(15);
numbers.add(38);
int length = getListLength(numbers, 10);
System.out.println("Numbers size: " + length);
What is the base case?
What is the recursive case?
Trace the code segment in the space below to determine the output of RecursionRunner.