Post

Created by @nathanedwards
 at November 1st 2023, 2:11:22 pm.

Question:

You are given an array arr of positive integers. Implement a method multiplyEven that multiplies every even element in the array arr by 2. The method should return the resulting array.

Method Signature:

public static int[] multiplyEven(int[] arr)

Input:

  • An array arr of positive integers, containing at least one element.

Output:

  • The method should return an array of the same length as arr with the even elements multiplied by 2.

Example:

int[] arr = {1, 2, 3, 4, 5};
int[] result = multiplyEven(arr);
System.out.println(Arrays.toString(result));

Output:

[1, 4, 3, 8, 5]

Answer:

The problem states that we need to multiply every even element in the given array arr by 2. We can approach this problem by iterating over the array, checking if each element is even, and multiplying it by 2 if it is.

Here is the step-by-step solution:

  1. Initialize a new array result of the same length as arr to store our final result.
  2. Iterate over the array arr using a for loop and index variable i.
  3. Inside the loop, check if arr[i] is even by using the modulus operator %. If arr[i] % 2 == 0, it means arr[i] is even.
  4. If arr[i] is even, multiply it by 2 and store the result in result[i].
  5. If arr[i] is odd, store it as it is in result[i].
  6. After the loop ends, return the result array.

Here is the implementation in Java:

public static int[] multiplyEven(int[] arr) {
    int n = arr.length;
    int[] result = new int[n];
    
    for (int i = 0; i < n; i++) {
        if (arr[i] % 2 == 0) {
            result[i] = arr[i] * 2;
        } else {
            result[i] = arr[i];
        }
    }
    
    return result;
}

Let's test the solution with the given example:

int[] arr = {1, 2, 3, 4, 5};
int[] result = multiplyEven(arr);
System.out.println(Arrays.toString(result));

Output:

[1, 4, 3, 8, 5]

The even elements in the arr array are {2, 4}. We can see that after multiplying them by 2, the resulting array contains {1, 4, 3, 8, 5}, which is the correct answer.