Q:

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;
}
2
// C program to rotate an array by 
// d elements 
#include <stdio.h> 
  
/* Function to left Rotate arr[] of size n by 1*/
void leftRotatebyOne(int arr[], int n); 
  
/*Function to left rotate arr[] of size n by d*/
void leftRotate(int arr[], int d, int n) 
{ 
    int i; 
    for (i = 0; i < d; i++) 
        leftRotatebyOne(arr, n); 
} 
  
void leftRotatebyOne(int arr[], int n) 
{ 
    int temp = arr[0], i; 
    for (i = 0; i < n - 1; i++) 
        arr[i] = arr[i + 1]; 
    arr[i] = temp; 
} 
  
/* utility function to print an array */
void printArray(int arr[], int n) 
{ 
    int i; 
    for (i = 0; i < n; i++) 
        printf("%d ", arr[i]); 
} 
  
/* Driver program to test above functions */
int main() 
{ 
    int arr[] = { 1, 2, 3, 4, 5, 6, 7 }; 
    leftRotate(arr, 2, 7); 
    printArray(arr, 7); 
    return 0; 
} 
1
// C++ program to rotate an array by 
// d elements 
#include <bits/stdc++.h> 
using namespace std; 
  
/*Fuction to get gcd of a and b*/
int gcd(int a, int b) 
{ 
    if (b == 0) 
        return a; 
  
    else
        return gcd(b, a % b); 
} 
  
/*Function to left rotate arr[] of siz n by d*/
void leftRotate(int arr[], int d, int n) 
{ 
    /* To handle if d >= n */
    d = d % n; 
    int g_c_d = gcd(d, n); 
    for (int i = 0; i < g_c_d; i++) { 
        /* move i-th values of blocks */
        int temp = arr[i]; 
        int j = i; 
  
        while (1) { 
            int k = j + d; 
            if (k >= n) 
                k = k - n; 
  
            if (k == i) 
                break; 
  
            arr[j] = arr[k]; 
            j = k; 
        } 
        arr[j] = temp; 
    } 
} 
  
// Function to print an array 
void printArray(int arr[], int size) 
{ 
    for (int i = 0; i < size; i++) 
        cout << arr[i] << " "; 
} 
  
/* Driver program to test above functions */
int main() 
{ 
    int arr[] = { 1, 2, 3, 4, 5, 6, 7 }; 
    int n = sizeof(arr) / sizeof(arr[0]); 
  
    // Function calling 
    leftRotate(arr, 2, n); 
    printArray(arr, n); 
  
    return 0; 
} 
1

New to Communities?

Join the community