C++ Program to Shift Every Element of An Array to Circularly Right

Hello Learners,

In this particular article, we are going to learn how to Circularly Right Shift Every Element of an Array in C++. The array can be user-defined or as well as by default given in the program. While and for loops are going to be used but Recursion is an alternative method to implement in this program.
Let us see an example for better understanding:
array[]={1 2 3 4 5}
here, we have to shift each and every element to right and the rightmost element will be the first element in the output screen.
Output screen will look like this:
array[]={5 1 2 3 4}

How to Circularly Right Shift Each and Every Element of an Array Using C++

let us create an array named arr[n]. Here, n is the size of the array which should be an integer. we are considering here only 5 elements but any other size is also accepted. It’s up to the user. Only you need to mention that in your program by just asking the user to enter the size of your array. Now here, We will use a while loop to circularly shift elements and for loop to display and enter the array in this program. This is called an iterative approach. Firstly, we will put the last element in a temporary variable as it has to be the first element of the array. Then, we’ll shift the rest elements to right by using variables i and j. Lastly, we will place the value stored in the temporary variable at the first position of that array. Our last task will be printing the elements of the array.

Underneath is the C++ codes to solve this problem:

using namespace std;

int main()
  int arr[5],i;

  cout<<"Enter elements of array: ";
        cout<<"Your array: ";
  cout<<arr[i]<<"  ";
  int j=i-1;
  int temp=arr[4];
    while(j>=0 && i>=0)
  cout<<"\nShifted array: ";
  cout<<arr[i]<<"  ";
  return 0;

Here, variable i is initialized to 4 which is the last index of the given array. So, variable i will work from index 4 to 1, and variable j is initialized to (i-1) which means at first it will be holding the value 3. After this, the element at index 3 will get swapped with the element at index 4. Then, i and j both will get decremented by 1 till it becomes equal to zero. Following this, every time each element will get shifted to the right. Lastly, the value of the temporary element will be placed at the first place of the array as the current index of i will be zero.

Let us see the output now:

Enter elements of aaray: 10
Your array: 10 20 30 40 50
Shifted array: 50 10 20 30 40

Some more Array Questions:
Maximum & Minimum element of an array using C++

In this way, you can circularly right shift elements of an array. I hope it was easy enough to understand. If you have any doubt, feel free to ask in the comment section.

Thank you!

Isha Rani Prasad
Codespeedy Tech Pvt. Ltd.

Leave a Reply

Your email address will not be published. Required fields are marked *