int[] a = {1, 2, 4, 5, 0};
// insert 3 at index 2; last slot is unused
for (int i = a.length - 1; i > 2; i--) {
a[i] = a[i - 1];
}
a[2] = 3;
System.out.println(a[0]+" "+a[1]+" "+a[2]+" "+a[3]+" "+a[4]);What is printed?
- Acheck_circle
1 2 3 4 5
- B
1 2 3 5 5
- C
1 2 3 4 0
- D
1 2 4 5 3
Explanation
To insert at index 2, we shift elements right, starting from the end (working backward to avoid overwriting). Then we put 3 at index 2.