I am taking the first steps in java, so my question is simple - I have an array with 8 integers, and I want to return an array containing elements of an odd index from the original array. what is wrong with slowing down the method? Any other implementation recommendations would be appreciated.
PS - I know that I do not need to use the method here, it's just for exercise.
package com.tau;
public class Main {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5, 6, 7, 8};
System.out.println("1.e odd index numbers in array : " + oddIndex(arr));
int j = 0;
public static int[] oddIndex(int[] array){
int newArrSize = array.length;
if ((newArrSize % 2) != 0) {
newArrSize--;
}
int[] newArr = new int[newArrSize];
for (int i = 0; i < array.length; i++)
if ((array[i] % 2) == 0) {
newArr[j] = array[i];
j++;
}
return newArr;
}
}
}
source
share