Question:
You have been given an array nums
of integers with a length of n
. Write a Java method traverseAndManipulate
that takes in this array and performs the following operations:
evenSum
.oddProduct
.The method should return the modified array with the replaced values at even indices. Assume that the length of nums
is always even.
Write the complete method traverseAndManipulate
with the following signature:
public static int[] traverseAndManipulate(int[] nums)
Example:
Input:
int[] nums = {1, 2, 3, 4, 5, 6, 7, 8};
Output:
// evenSum = 1+3+5+7 = 16
// oddProduct = 8*6*4*2 = 384
// After replacing elements at even indices: {8, 2, 6, 4, 384, 6, 5, 8}
Explanation:
To solve the problem, we can follow the following steps:
evenSum
as 0 and oddProduct
as 1 to keep track of values.nums
array from left to right using a for loop. In each iteration, check if the current index i
is even or odd using the modulus operator %
. If even, add the element at nums[i]
to evenSum
.nums
array from right to left using a for loop. In each iteration, check if the current index i
is even or odd using the modulus operator %
. If odd, multiply the element at nums[i]
to oddProduct
.nums
array once again using a for loop. In each iteration, check if the current index i
is even or odd using the modulus operator %
. If even, replace the element at nums[i]
with the value at nums[i-1]
.nums
array.Here is the implementation of the traverseAndManipulate
method:
public static int[] traverseAndManipulate(int[] nums) {
int evenSum = 0;
int oddProduct = 1;
// Step 1: Find sum of elements at even indices
for (int i = 0; i < nums.length; i++) {
if (i % 2 == 0) {
evenSum += nums[i];
}
}
// Step 2: Find product of elements at odd indices
for (int i = nums.length - 1; i >= 0; i--) {
if (i % 2 == 1) {
oddProduct *= nums[i];
}
}
// Step 3: Replace elements at even indices
for (int i = 0; i < nums.length; i++) {
if (i % 2 == 0) {
nums[i] = nums[i + 1];
}
}
// Step 4: Return modified array
return nums;
}
This implementation correctly traverses the array, performs the required operations, and returns the modified array with replaced values at even indices.