Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

C Program for Program to cyclically rotate an array by one

  • Last Updated : 26 Dec, 2021

Given an array, cyclically rotate the array clockwise by one.

Examples:

Input:  arr[] = {1, 2, 3, 4, 5}
Output: arr[] = {5, 1, 2, 3, 4}

Recommended: Please solve it on “PRACTICE” first, before moving on to the solution.

C++




// C++ code for program 
// to cyclically rotate
// an array by one
# include <iostream>
using namespace std;
  
void rotate(int arr[], int n)
{
    int x = arr[n - 1], i;
    for (i = n - 1; i > 0; i--)
    arr[i] = arr[i - 1]; 
    arr[0] = x;
}
  
// Driver code
int main() 
{
    int arr[] = {1, 2, 3, 4, 5}, i;
    int n = sizeof(arr) / 
            sizeof(arr[0]);
  
    cout << "Given array is \n";
    for (i = 0; i < n; i++)
        cout << arr[i];
  
    rotate(arr, n);
  
    cout << "\nRotated array is\n";
    for (i = 0; i < n; i++)
        cout << arr[i];
  
    return 0;
}
  
// This code is contributed by jit_t


C




#include <stdio.h>
  
void rotate(int arr[], int n)
{
   int x = arr[n-1], i;
   for (i = n-1; i > 0; i--)
      arr[i] = arr[i-1];
   arr[0] = x;
}
  
int main()
{
    int arr[] = {1, 2, 3, 4, 5}, i;
    int n = sizeof(arr)/sizeof(arr[0]);
  
    printf("Given array is\n");
    for (i = 0; i < n; i++)
        printf("%d ", arr[i]);
  
    rotate(arr, n);
  
    printf("\nRotated array is\n");
    for (i = 0; i < n; i++)
        printf("%d ", arr[i]);
  
    return 0;
}

Please refer complete article on Program to cyclically rotate an array by one for more details!


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!