Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

• Write a recursive method with method header void printArray(int[] a, int size)

ID: 3631951 • Letter: #

Question

• Write a recursive method with method header void printArray(int[] a, int size) that prints the first size elements of array a on separate lines.
? printArray(…) should check to make sure size is a positive number less than or equal to the length of array a – if not, it should print out an error message and use System.exit(0) to exit the program.
? If size is 0, printArray(…) should return without printing anything.
? If size is 1, printArray(…) should print a[0] and return.
? If size is > 1, printArray(…) should call printArray(a, size-1), then print a[size-1], and then return.

• Write a main(…) method to test printArray(…) using an int array that you create in main(…) and any valid size you want. The array should contain several different non-zero values.

Explanation / Answer

public class rec
{

        public static void main(String[] args)
        {
                        int[] array = new int[4];
                        array[0] = 1;
                        array[1] = 2;
                        array[2] = 3;
                        array[3] = 4;
                        printArray(array, 3);
        }

        public static void printArray(int[] a, int size){
        if(size < 0) {
        System.out.println("Error! Can't have negative size.");
        System.exit(0);
        return;
        }
        if(size == 0){
        return;
        }
        if(size == 1){
        System.out.println(a[0]);
        return;
        }
        System.out.println(a[0]);
        int[] temp = new int[a.length-1];
        for(int i =0; i<temp.length; i++){
                temp[i] = a[i+1];
        }
        printArray(temp,size-1);
        }
}