Question 19
Back to Exercise
What is the output of the following Java program?
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] a = {1, 2, 3, 4, 5, 6};
int k = 8;
int n = a.length;
int[] r = new int[n];
for (int i = 0; i < n; i++) r[(i + k) % n] = a[i];
System.out.println(Arrays.toString(r));
}
}
- A [5, 6, 1, 2, 3, 4] Correct
- B [3, 4, 5, 6, 1, 2]
- C [6, 1, 2, 3, 4, 5]
- D ArrayIndexOutOfBoundsException
Correct Answer: Option A
Rotating by 8 on 6 elements is the same as rotating by 2; % n wraps indexes around.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!