Question 4
The following method is intended to shift all elements in an array one position to the right, with the last element wrapping around to position 0.
public static void shiftRight(int[] arr)
{
for (int i = arr.length - 1; i > 0; i--)
{
arr[i] = arr[i - 1];
}
}
The method does not work as intended. For example, when called with the array {1, 2, 3, 4}, the method produces {1, 1, 2, 3} instead of the expected {4, 1, 2, 3}.
The method does not work as intended. For example, when called with the array {1, 2, 3, 4}, the method produces {1, 1, 2, 3} instead of the expected {4, 1, 2, 3}.
Which of the following changes can be made so that the method works as intended?
- AChange the loop to start at i = 0 and go to i < arr.length - 1, incrementing i
- BBefore the loop, store arr[arr.length - 1] in a temporary variable, then after the loop, assign the temporary variable to arr[0]
- CChange arr[i] = arr[i - 1] to arr[i - 1] = arr[i]
- DChange the loop condition from i > 0 to i >= 0
Show answer and explanation
Answer: B
The current method shifts elements right correctly by copying each element from position i-1 to position i, working from right to left. However, it loses the last element because the first copy (arr[arr.length-1] = arr[arr.length-2]) overwrites the original last value before it can be placed at index 0. The fix is to save the last element in a temporary variable before the loop starts, then assign it to arr[0] after the loop completes. Changing the loop direction or reversing the assignment would shift left instead of right.