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.
public static int[] multiplyEven(int[] arr)
arr of positive integers, containing at least one element.arr with the even elements multiplied by 2.int[] arr = {1, 2, 3, 4, 5};
int[] result = multiplyEven(arr);
System.out.println(Arrays.toString(result));
Output:
[1, 4, 3, 8, 5]
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:
result of the same length as arr to store our final result.arr using a for loop and index variable i.arr[i] is even by using the modulus operator %. If arr[i] % 2 == 0, it means arr[i] is even.arr[i] is even, multiply it by 2 and store the result in result[i].arr[i] is odd, store it as it is in result[i].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.