A recursive function that prints out an array in reverse.

public class RecursiveMin {
    public static void main (String [] args) {
	int [] a = {4, 6, 3, 7, 2, 8};
	ArrayObj ao = new ArrayObj(a);
	ao.reversePrint();
    }
}

class ArrayObj {
    private int [] arr;

    public ArrayObj(int [] a) {
	// creating a local copy of the array
	arr = new int[a.length];
	for (int i = 0; i < a.length; ++i) {
	    arr[i] = a[i]; 
	}
    }
    public void reversePrint() {
	reversePrintHelper(0);
    }

    private void reversePrintHelper(int i) {
	if (i == arr.length - 1) {
	    System.out.println(arr[i]);
	} else {
	    reversePrintHelper(i + 1);
	    System.out.println(arr[i]);
	}
    }
    
}

This is an example from CSci 1211 course.

The views and opinions expressed in this page are strictly those of the page author. The contents of this page have not been reviewed or approved by the University of Minnesota.