Rotate Array Elements to the Left by Two Positions in C
In this tutorial, we will write a C program to rotate the elements of an array to the left by two positions.
Problem Statement
Write a C program to rotate the elements of an array to the left by two positions. After rotation:
- The first element becomes the second last.
- The second element becomes the last.
- All other elements shift two positions to the left.
Example
Original Array: 1 2 3 4 5 After Rotation: 3 4 5 1 2
Algorithm
- Store the first two elements in temporary variables.
- Shift the remaining elements two positions to the left.
- Place the stored elements at the end of the array.
C Program
#include <stdio.h>
int main() {
int arr[100], n, i;
int temp1, temp2;
printf("Enter number of elements: ");
scanf("%d", &n);
printf("Enter %d elements:\n", n);
for(i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// Check if array has at least 2 elements
if(n < 2) {
printf("Rotation not possible.\n");
return 0;
}
// Store first two elements
temp1 = arr[0];
temp2 = arr[1];
// Shift elements left by 2 positions
for(i = 0; i < n - 2; i++) {
arr[i] = arr[i + 2];
}
// Place stored elements at the end
arr[n - 2] = temp1;
arr[n - 1] = temp2;
printf("Array after left rotation by 2 positions:\n");
for(i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
Explanation
Step 1: Input
The user enters the number of elements and the array values.
Step 2: Store First Two Elements
We store the first two elements in temporary variables:
temp1 = arr[0];
temp2 = arr[1];
Step 3: Shift Elements
We move each element two positions left:
for(i = 0; i < n - 2; i++) {
arr[i] = arr[i + 2];
}
Step 4: Place Stored Elements at End
Finally, we place the stored elements at the last two positions:
arr[n - 2] = temp1;
arr[n - 1] = temp2;
Time Complexity
The program uses a single loop to shift elements. Therefore, the time complexity is O(n).
কোন মন্তব্য নেই:
একটি মন্তব্য পোস্ট করুন