c++ shift array to the right

To shift an array to the right in C++, you can follow these steps:

  1. Declare and initialize an array: Start by declaring and initializing an array with the desired elements. For example:
int arr[] = {1, 2, 3, 4, 5};
  1. Determine the size of the array: Use the sizeof operator to determine the size of the array in bytes, and divide it by the size of an individual element to get the number of elements in the array. For example:
int size = sizeof(arr) / sizeof(arr[0]);
  1. Store the last element: Create a temporary variable to store the last element of the array. This will be used to shift the elements to the right. For example:
int temp = arr[size - 1];
  1. Shift the elements to the right: Iterate over the array from the second-to-last element to the first element using a loop. Copy each element to its right neighbor. For example:
for (int i = size - 1; i > 0; i--) {
    arr[i] = arr[i - 1];
}
  1. Assign the stored element to the first position: Assign the stored element to the first position in the array. For example:
arr[0] = temp;
  1. Print the shifted array: Iterate over the array and print its elements to verify the result. For example:
for (int i = 0; i < size; i++) {
    cout << arr[i] << " ";
}

Here is the complete code:

#include <iostream>
using namespace std;

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    int size = sizeof(arr) / sizeof(arr[0]);
    int temp = arr[size - 1];

    for (int i = size - 1; i > 0; i--) {
        arr[i] = arr[i - 1];
    }

    arr[0] = temp;

    for (int i = 0; i < size; i++) {
        cout << arr[i] << " ";
    }

    return 0;
}

This code will shift the array to the right by one position. The output will be: 5 1 2 3 4.