Exercises 4
18.12 What does the following program do?
18.13 What does the following program do?
1// Exercise 18.12: MysteryClass.java
2public class MysteryClass {
3 public static int mystery(int[] array2, int size) {
4 if (size == 1) {
5 return array2[0];
6 }
7 else {
8 return array2[size – 1] + mystery(array2, size – 1);
9 }
10 }
11
12 public static void main(String[] args) {
13 int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
14
15 int result = mystery(array, array.length);
16 System.out.printf(“Result is: %d%n”, result);
17 }
18 }
1// Exercise ANS: : SomeClass.java
2public class SomeClass {
3 public static String someMethod(int[] array2, int x)
4 if (x < array2.length) {
5 return String.format(
6 “%s%d “, someMethod(array2, x + 1), array2[x]);
7 }
8 else {
9 return “”;
10 }
11 }
12
13 public static void main(String[] args) {
14 int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
15 String results = someMethod(array, 0);
16 System.out.println(results);
17 }
18 }
© 2018 Pearson Education, Inc., 330 Hudson Street, NY NY 10013. All rights reserved.