How to Separate Numbers Into Odd & Even in Java

An integer number is even if it is exactly divisible by 2; it is odd otherwise. You can write a program in the Java programming language that tests each element in an input array for this property, and separates the elements into separate Collections -- one for even, one for odd.

Instructions

    • 1

      Store the set of input integers as elements in an array, as in the following sample code:

      int[] inputNumbers = {43,543,245,2,56,567,8767,2,-32,41};

    • 2

      Declare two Java Collections to hold even numbers separately from odd ones, as in the following sample code:

      List<Integer> outputEven = new ArrayList<Integer>();

      List<Integer> outputOdd = new ArrayList<Integer>();

      The advantage of using Collections is that, in addition to providing many useful built-in methods, Collections only use memory for as many elements as they contain.

    • 3

      Separate the numbers into the two output Collections by iterating over the input, as in the following sample code:

      for (int i: inputNumbers) {

      if (i % 2 != 0) {

      outputOdd.add(i);

      } else {

      outputEven.add(i);

      }

      }

      After executing this code, Collections outputEven and outputOdd will contain the even and odd numbers in the input, respectively.

Related Searches:

Resources

Comments

You May Also Like

Related Ads

Featured