Question 18
Back to Exercise
What is the output of the following Java program?
public class Main {
static int sum(int[] a, int i) {
return i == a.length ? 0 : a[i] + sum(a, i + 1);
}
static int max(int[] a, int i) {
if (i == a.length - 1) return a[i];
return Math.max(a[i], max(a, i + 1));
}
public static void main(String[] args) {
int[] a = {4, 11, 7, 2, 9};
System.out.println(sum(a, 0) + " " + max(a, 0) + " " + sum(a, 3));
}
}
- A 33 11 11 Correct
- B 33 11 2
- C 33 9 11
- D 22 11 11
Correct Answer: Option A
The index moves forward each call; sum(a, 3) adds only the last two elements, 2 + 9.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!