To rotate elements in an array in C, you can use a temporary array or perform the rotation in place using loops. The rotation can be either to the left or to the right, depending on your requirements.
In this example,
arr
with integer values.n
to specify the number of elements in the array and a variable k
to specify the number of positions to rotate.#include <stdio.h>
void rotateLeft(int arr[], int n, int k) {
int temp[n];
for (int i = 0; i < n; i++) {
temp[i] = arr[(i + k) % n];
}
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 positions to rotate
rotateLeft(arr, n, k);
printf("Rotated array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
Rotated array: 3 4 5 1 2
In this example,
arr
with integer values.n
to specify the number of elements in the array and a variable k
to specify the number of positions to rotate.#include <stdio.h>
void rotateRight(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 positions to rotate
rotateRight(arr, n, k);
printf("Rotated array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
Rotated array: 4 5 1 2 3
In this tutorial, we learned How to Rotate Elements in an Array in C language with well detailed examples.