Python/C/C++/JAVA

Moderate Practice Programs with Code and Concept

By D.S

Array Rotation

So you've got an array and need to rotate it by a certain number of positions? Well, good news - there are plenty of programming languages that can help make this task easier. In C and C++, the simplest approach is to use a for loop, copying each element in the original array to its new position after being shifted by the number of rotations specified. Python offers some built-in functions like list slicing and concatenation that makes it even easier! Meanwhile, Java has several ways to rotate arrays such as using traditional loops or using swapping elements technique. Regardless of which language you're working with, array rotation is an important skill to have as it can be used in various different applications from game development to data processing.

(a.) C Code

#include <stdio.h>>

void rotate(int arr[], int n, int k) {
int temp[n];
for (int i = 0; i < n; i++) {
    temp[(i + k) % n] = arr[i];
}
for (int i = 0; i < n; i++) {
    arr[i] = temp[i];
}
}

int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
int k = 2;  // Number of rotations
rotate(arr, n, k);
printf("Rotated Array: ");
for (int i = 0; i < n; i++) {
    printf("%d ", arr[i]);
}
return 0;
}
Output:-
Rotated Array: 4 5 1 2 3

(b.) C++ Code

#include <iostream>
using namespace std;

void rotate(int arr[], int n, int k) {
int temp[n];
for (int i = 0; i < n; i++) {
    temp[(i + k) % n] = arr[i];
}
for (int i = 0; i < n; i++) {
    arr[i] = temp[i];
}
}

int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
int k = 2;  // Number of rotations
rotate(arr, n, k);
cout << "Rotated Array: ";
for (int i = 0; i < n; i++) {
    cout << arr[i] << " ";
}
return 0;
}
Output:-
Rotated Array: 4 5 1 2 3

(c.) Python Code

def rotate(arr, k):
n = len(arr)
k = k % n  # In case the number of rotations is greater than array length
return arr[-k:] + arr[:-k]

arr = [1, 2, 3, 4, 5]
k = 2  # Number of rotations
rotated_arr = rotate(arr, k)
print("Rotated Array:", rotated_arr)
Output:-
Rotated Array: [4, 5, 1, 2, 3]

(d.) Java Code

import java.util.Arrays;

public class ArrayRotation {
public static void rotate(int[] arr, int k) {
    int n = arr.length;
    k = k % n;  // In case the number of rotations is greater than array length
    reverse(arr, 0, n - 1);
    reverse(arr, 0, k - 1);
    reverse(arr, k, n - 1);
}

public static void reverse(int[] arr, int start, int end) {
    while (start < end) {
        int temp = arr[start];
        arr[start] = arr[end];
        arr[end] = temp;
        start++;
        end--;
    }
}

public static void main(String[] args) {
    int[] arr = {1, 2, 3, 4, 5};
    int k = 2;  // Number of rotations
    rotate(arr, k);
    System.out.println("Rotated Array: " + Arrays.toString(arr));
}
}
Output:-
Rotated Array: [4, 5, 1, 2, 3]