Let m be an input array of integers. First, we'll output the last element of the array m[n – 1]. Then, we will sequentially output all the numbers from m[0] to m[n – 2].
Consider an implementation in which the elements of the array will actually be rearranged. For this, it is necessary to move the element from the (i – 1)-th cell to the i-th cell of the array, 1 ≤ i ≤ n – 1. Separately, the element from the (n – 1)-th cell should be moved to the 0-th cell.
Algorithm Implementation
Declare an integer array m.
int m[101];Read the input numbers into array m.
scanf("%d",&n);
for(i = 0; i < n; i++)
scanf("%d",&m[i]);First, we'll output the last number of the array m[n – 1] – it will be the first after the cyclic shift of elements by one position to the right.
printf("%d",m[n-1]);Then, we'll output all the numbers of the array, starting from the zeroth m[0] to the penultimate m[n – 2].
for(i = 0; i < n - 1; i++)
printf(" %d",m[i]);
printf("\n");Implementation – with rearrangement of elements
Declare an integer array m.
int m[101];Read the input numbers into array m.
scanf("%d",&n);
for(i = 0; i < n; i++)
scanf("%d",&m[i]);Remember the last element m[n – 1] in the variable temp.
temp = m[n-1];Move the element m[i – 1] to m[i] (1 ≤ i ≤ n – 1).
for(i = n - 1; i > 0; i--)
m[i] = m[i - 1];Assign the element that was at the end of the array to the beginning of the array.
m[0] = temp;Output the resulting array.
for(i = 0; i < n; i++)
printf("%d ",m[i]);
printf("\n");Implementation – STL rotate
Declare an integer vector.
vector<int> v;Read the input data.
scanf("%d", &n);
v.resize(n);
for (i = 0; i < n; i++)
scanf("%d", &v[i]);Perform a shift of the array elements so that the last element becomes the first.
rotate(v.begin(), v.begin() + n - 1, v.end());Output the resulting array.
for (i = 0; i < n; i++)
printf("%d ", v[i]);
printf("\n");Implementation – dynamic array
#include <stdio.h>
int i, n, a;
int *m;
int main(void)
{
scanf("%d",&n);
m = new int[n];
for(i = 0; i < n; i++)
scanf("%d",&m[i]);
printf("%d",m[n-1]);
for(i = 0; i < n - 1; i++)
printf(" %d",m[i]);
printf("\n");
delete[] m;
return 0;
}Java Implementation
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner con = new Scanner(System.in);
int n = con.nextInt();
int m[] = new int[n];
for(int i = 0; i < n; i++)
m[i] = con.nextInt();
System.out.print(m[n-1]);
for(int i = 0; i < n - 1; i++)
System.out.print(" " + m[i]);
System.out.println();
con.close();
}
}Python Implementation
n = int(input())
v = list(map(int, input().split()))
v = v[-1:] + v[:-1]
for num in v:
print(num, end=" ")
print()