Post

Created by @nathanedwards
 at November 1st 2023, 2:35:15 pm.

Question:

Write a Java method manipulateArray that takes in an array of integers and performs the following manipulations:

  1. Find the sum of all the elements in the array.
  2. Reverse the order of the elements in the array.
  3. Double the value of each element in the array.
  4. Replace every odd element in the array with 0.

The method signature is:

public static void manipulateArray(int[] arr)

Example:

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

Output: [0, 8, 0, 8, 0]

Explanation:

  1. The sum of the elements in the original array [1, 2, 3, 4, 5] is 1 + 2 + 3 + 4 + 5 = 15.
  2. After reversing the array, it becomes [5, 4, 3, 2, 1].
  3. Doubling the elements gives [10, 8, 6, 4, 2].
  4. Replacing the odd elements with 0 leaves us with [0, 8, 0, 8, 0].

Solution:

import java.util.Arrays;

public class ArrayManipulation {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};
        manipulateArray(arr);
        System.out.println(Arrays.toString(arr));
    }

    public static void manipulateArray(int[] arr) {
        int sum = 0;
        
        // Find the sum of all elements in the array
        for (int num : arr) {
            sum += num;
        }
        
        // Reverse the order of the elements in the array
        for (int i = 0; i < arr.length / 2; i++) {
            int temp = arr[i];
            arr[i] = arr[arr.length - 1 - i];
            arr[arr.length - 1 - i] = temp;
        }
        
        // Double the value of each element in the array
        for (int i = 0; i < arr.length; i++) {
            arr[i] *= 2;
        }
        
        // Replace every odd element with 0
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] % 2 != 0) {
                arr[i] = 0;
            }
        }
    }
}

In this solution, we have implemented the manipulateArray method that performs the required manipulations on the input array.

First, we calculate the sum of all the elements in the array using a for-each loop and the sum variable.

Next, we reverse the order of the elements in the array using a for loop and swapping the elements at the corresponding indices.

Then, we double the value of each element in the array using a for loop and the multiplication operator.

Finally, we replace every odd element with 0 using another for loop and the modulo operator to check for oddness.

After calling the manipulateArray method with the given example array, we print the modified array using Arrays.toString to verify the output.

The output of the provided example is [0, 8, 0, 8, 0], which matches the expected result.