Write a recursive method with method header void printArray(int[]a,int size) tha
ID: 3631929 • Letter: W
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 apositive number less than or equal to the length of the array a-if not , it should print out an error message and use System.eit(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. Then 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);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.