JAVA!!! The elements of an integer -valued array can be initialized so that a[i]
ID: 3926125 • Letter: J
Question
JAVA!!!
The elements of an integer -valued array can be initialized so that a[i] == i in a recursive fashion as follows: An array of size 0 is already initialized ; Otherwise set the last element of the array to n-1 (where n is the number of elements in the array , for example, an array of size 3 will have its last element -- index 2-- set to 2; and initialize the portion of the array consisting of the first n-1 elements (i.e., the other elements of the array ) Write a void method named init that accepts an integer array , and the number of elements in the array and recursively initializes the array so that a[i] == i.
Explanation / Answer
InitArray.java
import java.util.Arrays;
public class InitArray{
public static void main(String[] args) {
int a[] = new int[3];
init(a, 3);
System.out.println(Arrays.toString(a));
}
public static void init (int a[],int size){
if(size==0){
return;
}
else{
a[size-1]=size-1;
init(a,size-1);
}
}
}
Output:
[0, 1, 2]
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.