Consider the following Java code:
public class ArrayTraversal {
public static int[] modifyArray(int[] arr) {
int[] modifiedArr = new int[arr.length];
// Step 1: Traversing the array arr backwards
for (int i = arr.length - 1; i >= 0; i--) {
// Step 2: Doubling the value of the current element
modifiedArr[i] = arr[i] * 2;
}
return modifiedArr;
}
public static void main(String[] args) {
int[] myArray = {1, 2, 3, 4, 5};
// Step 3: Calling the modifyArray method
int[] modifiedArray = modifyArray(myArray);
// Step 4: Printing the modified array
for (int element : modifiedArray) {
System.out.print(element + " ");
}
}
}
What will be the output when the above code is executed?
A) 1 2 3 4 5 B) 2 4 6 8 10 C) 10 8 6 4 2 D) 5 4 3 2 1
Explain your answer with the detailed step-by-step explanation of the code.
The correct output will be B) 2 4 6 8 10.
Explanation:
We define a class ArrayTraversal
with a public static method modifyArray
that takes an integer array arr
as input and returns an integer array.
In the modifyArray
method, we first declare a new integer array modifiedArr
with the same length as arr
.
Next, we traverse the array arr
backwards starting from the last index (arr.length - 1
) to the first index (0), inclusive, using a for loop.
In each iteration of the loop, we double the value of the current element arr[i]
and assign it to the corresponding element in modifiedArr
using the same index i
.
Finally, we return the modifiedArr
array.
In the main
method, we create an integer array myArray
with the values {1, 2, 3, 4, 5}.
We then call the modifyArray
method, passing myArray
as the argument, and assign the returned array to modifiedArray
.
We use a for-each loop to traverse the modifiedArray
and print each element followed by a space. The output of this loop will be "2 4 6 8 10".
Therefore, the correct answer is B) 2 4 6 8 10.