Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove odd-valued elements from an array?

Tags:

java

arrays

My objective is to write a method that creates a copy of an array with the odd numbers removed. Here is my code:

public class Evens {
    static int[] evens(int[] input) {
        final int n = input.length;
        int[] output = new int[n];
        for(int i=0;i<n;i++) {
            if(input[i]%2 == 0)
                output[i] = input[i];
        }
        return output;
    }
    public static void main(String[] args) {
        int[] fvalues = new int[] {4,7,9,3,6,8,2};
        int[] evalues = evens(fvalues);
        for(int i=0;i<evalues.length;i++)
            System.out.println(i+"] "+evalues[i]);
    }
}

When I run it, It gives me the elements of an array with all the even numbers of the original array but with zeros where the odd numbers were. How can I write it so there are no zeros with the odd numbers just gone?

like image 410
Dylan Broussard Avatar asked Jul 04 '26 01:07

Dylan Broussard


1 Answers

For removing an element you're better off using an ArrayList, since an array can't change its size. If you have to use arrays, then the output array must be shorter than the input. Say, if you're going to remove three elements, then the size of output will have to be input.length-3.

In your implementation, you're not actually removing elements, you just skip over the odd numbers, and since an int[] is initialized by default to zeros, the places where the odd numbers used to be appear with zeros on them.

You can do this:

  1. Calculate the number of even elements
  2. Create a new output array with the length found on the previous step
  3. Copy only the even numbers to the output array. It's a bit tricky, since you'll need to use two indexes (but only a single for loop): one index for iterating over the input array, and the other for iterating over the output array - the index for the input array gets incremented as usual, for every step of the iteration, but the index for the output array gets incremented only after adding a new even element to the output.
like image 158
Óscar López Avatar answered Jul 06 '26 16:07

Óscar López



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!