I know this loop will print {5, 1, 2, 3, 4} which is intended. The question here is how does the line below work?
values[i + 1] = values[i];
From what I understand, during the first loop, i = 3. So it will be values[3+1] = values[3] which would mean on the 4th index there will be the element of 3. Which is clearly wrong as that is not how the code works as the output is different.
int[] values = new int[]
{1, 2, 3, 4, 5};
int temp = values[values.length - 1];
for (int i = values.length - 2; i >= 0; i--)
{
values[i + 1] = values[i];
}
values[0] = temp;
System.out.println(Arrays.toString(values));
The code shifts the elements of the array to the right and shifts the rightmost element to the leftmost position.
Please explain to me because I am confused. Thank you.