ChallengeChallenge

Task

Your task is to write a method to sort an integer array in such a way that it contains only even values (even numbers are those that are divisible by 2 without a remainder). After that, in the main method, you need to print them to the console. I've already written a method for displaying the array on the screen, so don't worry about it.

This task is a great opportunity to learn a new operator. The % operator returns the remainder of a division operation. For example, 5 % 2 = 1. This is because 5 does not divide evenly by 2, so when we divide 5 by 2, we have a remainder of 1. You can use this operator in the task to check if a number is even. Use the if syntax: if (element % 2 == 0) - this expression will check if the number is even and return true or false.

java

Main.java

  1. 1. Create an integer variable, and initialize it with the value 0;
    1. 2. Using a for-each loop, iterate through the entire array and check if the number is even. If the answer is true, increment the size by 1;
    2. 3. Create a new integer array called result with a size equal to the previously calculated size;
    3. 4. Create an index variable and initialize it to 0;
    4. 5. Using a for-each loop, check if the number is even. If the answer is true, use result[index] = element;, then increment the value of the index. Alternatively, you can use the syntax result[index++] = element;;
    5. 6. Finally, return the result array from the method.

package com.example;

public class Main {
    static int[] sortIntArrayOnlyEvenNumbers(int[] input) {
        int size = 0;
        for (int element : input) {
            if (element % 2 == 0) {
                size++;
            }
        }
        int[] result = new int[size];
        int index = 0;
        for (int element : input) {
            if (element % 2 == 0) {
                result[index] = element;
                index++;
            }
        }
        return result;
    }

    // do not change code from below
    public static void main(String[] args) {
        int[] firstArray = {2, 0, 7, 4, 5, 13, 6, 8, 10, 49, 28, -4, 5, 3};
        int[] secondArray = {0, 1, 4, 5, 1, 6, 2, 7, 81, 20, 10, 44, 11, 7};
        printArray(sortIntArrayOnlyEvenNumbers(firstArray));
        printArray(sortIntArrayOnlyEvenNumbers(secondArray));
    }
    // do not change the code above


    // do not change code from below
    static void printArray(int[] array) {
        for (int element : array) {
            System.out.print(element + " ");
        }
        System.out.println();
    }
    // do not change the code above
}

      

Everything was clear?

Section 2. Chapter 8