Add a main so that you can put some code there to call your functions and make s
ID: 3882665 • Letter: A
Question
Add a main so that you can put some code there to call your functions and make sure they work:
public static void main(String[] args) { /* your testing code goes here */ }
Functions you should add if the functionality is possible. Otherwise add an empty function definition with a comment saying "impossible".
Problem #3
public static int[] getEveryOther(int[] values) {
/* This function should return a new array that contains every other value contained in the values array. In other words, the function should return a new array containing the values from positions 0, 2, 4, 6…. and input array values should remain unchanged.
*/ Test input: an empty ArrayList, an ArrayList with 5 values, and ArrayList with 6 value. If you make the values in the arraylist consecutive, it'll be very easy to see whether you are right; for example: 6, 7, 8, 9, 10.
Explanation / Answer
public class HelloWorld{
public static void main(String []args){
int[] inputArray1=new int[]{6,7,8,9,10};
int[] inputArray2=new int[]{20,21,22,23,24,25};
int[] outputArray= new int[]{};
//When input is of odd length.
System.out.println("Output 1 : ");
outputArray= getEveryOther(inputArray1);
for(int i=0;i<outputArray.length;i++){
System.out.println(outputArray[i]);
}
//When input is of even length.
System.out.println(" Output 2 : ");
outputArray= getEveryOther(inputArray2);
for(int i=0;i<outputArray.length;i++){
System.out.println(outputArray[i]);
}
}
public static int[] getEveryOther(int[] values){
//Length of input array
int len=values.length;
//If input's length is even, then output array's length will be len/2, else (len/2)+1
if(len%2==0){
len/=2;
}
else{
len=(len/2)+1;
}
int[] outArray=new int[len];
int i=0,j=0;
while(j<len){
outArray[j]=values[i];
//increment i by 2 to get every other value.
i+=2;
j+=1;
}
return outArray;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.