Problem statement: Cyclically rotate an array by one in C

 Example: input[] = {1, 2, 3, 4, 5, 6}; output[] = {6, 1, 2, 3, 4, 5};

Store the last element in a temp variable.
Traverse and Shift all elements one by one by a position ahead.
Replace the first element of the array with the temp variable.

```//Cyclically rotate an array by one in C
#include <stdio.h>

/*----Function to rotate an array cyclyically by one ----*/
void rotateByOne(int arr[], int n)
{
int temp = arr[n - 1], i;
for (i = n - 1; i > 0; i--)
arr[i] = arr[i - 1];
arr[0] = temp;
}

void printArray(int arr[], int n)
{
for (int i = 0; i < n; i++)
printf("%d\t", arr[i]);
}

int main()
{
int n;
printf("Enter the number of element\t");
scanf("%d", &n);
int arr[n];
printf("Enter array elements\n");
for (int i = 0; i < n; i++)
scanf("%d", &arr[i]);
printf("Array elements are:\n");
printArray(arr, n);
rotateByOne(arr, n);
printf("\nArray elements after rotation:\n");
printArray(arr, n);
}

```
 \$ gcc rotByOne.c \$ ./a.out Enter the number of element 5 Enter array elements 1 2 3 4 5 Array elements are: 1 2 3 4 5 Array elements after rotation: 5 1 2 3 4 \$
 Time complexity: O(n)

also see

Previous articleGet started with Go
Next articleCyclically rotate an array by k elements in C