public class ReverseArray
1: import java.util.Arrays;
3: /**
4: * A program to print arrays in reverse order using recursion.
5: *
6: * @author Mark Young (A00000000)
7: */
8: public class ReverseArray {
10: public static void main(String[] args) {
11: // create two sample arrays
12: int[] arr1 = new int[]{6, 100, 3, -2, 8, 18, 5};
13: int[] arr2 = new int[]{42, 17, -5, 86, 99};
15: // show the first one in reverse order
16: System.out.println();
17: System.out.print(Arrays.toString(arr1) + " in reverse: ");
18: printInReverse(arr1, arr1.length);
19: System.out.println();
21: // show the second one in reverse order
22: System.out.println();
23: System.out.print(Arrays.toString(arr2) + " in reverse: ");
24: printInReverse(arr2, arr2.length);
25: System.out.println();
26: }
28: /**
29: * Print the front part of an array in reverse order.
30: * Requires to be told how much of the array to print.
31: * (Uses recursion.)
32: *
33: * @pre 0 <= len < arr.length
34: * @post the elements arr[0..len-1] have been printed in reverse order.
35: *
36: * @param arr the array to be printed in reverse order
37: * @param len the part of the array to be printed (must be at front)
38: */
39: public static void printInReverse(int[] arr, int len) {
40: if (len > 0) {
41: // first print out the last element...
42: System.out.print(arr[len - 1] + " ");
43: // ... then print out the rest
44: printInReverse(arr, len - 1);
45: }
46: }
48: }