how to rotate elements in array code example

Example 1: rotate an array right in c

// C program to rotate an array cyclically

#include <stdio.h>

void rightRotateByOne(int arr[], int n) //function for cyclically rotating an array once
{
   int x = arr[n-1], i;
   for (i = n-1; i > 0; i--)
      arr[i] = arr[i-1];
   arr[0] = x;
}

int main()
{int t;
scanf("%d",&t);//number of test cases
int p;
for(p=0;p<t;p++){
    int n,i,k;
    scanf("%d %d",&n,&k); // n--> size of array ; k--> number of rotations
    int arr[n];
    k=k%n;
    for(i=0;i<n;i++){
        scanf("%d",&arr[i]);
    }
int j;
 for(j=0;j<k;j++) //cyclically rotating an array k times
{rightRotateByOne(arr, n);}


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

    return 0;
}

Example 2: rorate array

function rotateArray(A, K) {
    if (!A.length) return A;
    let index = -1;
    while (++index < K) {
        A.unshift(A.pop());
    }
    return A;
}

[
    rotateArray([3, 8, 9, 7, 6], 3),
    rotateArray([0, 0, 0], 1),
    rotateArray([1, 2, 3, 4], 4),
    rotateArray([], 4),
].join(' | ');

Tags:

C Example