Recursive Function to Print an Array (Version 2)


public class RecArrayPrint2 {
    public static void main(String[] args) {

        int[] values = {10,20,30,40,50};

        recArrayPrint(values,5);
    }

//  print values in array
    static void recArrayPrint(int array[],int size) {
        if (size > 0) {
            System.out.print(array[0] + "   ");
// arraycopy copies size-1 entries from array starting in loc 1,
// to array starting in loc 0 (in other words, it cuts off the
// first element of the array
            System.arraycopy(array,1,array,0,size-1);
            recArrayPrint(array,size-1);
        }

//  base case is empty array (size == 0), so
//  just print newline
        else
            System.out.println();
    }
}

Output


10   20   30   40   50


Email Me | Office Hours | My Home Page | Department Home | MCC Home Page

© Copyright Emmi Schatz 2008