Rotate Array Elements to the Right by One Position in C
In this tutorial, we will write a C program to rotate the elements of an array to the right by one position.
Problem Statement
Write a C program to rotate the elements of an array to the right by one position. After rotation:
- The last element becomes the first element.
- All other elements shift one position to the right.
Example
Original Array: 1 2 3 4 5 After Rotation: 5 1 2 3 4
Algorithm
- Store the last element in a temporary variable.
- Shift all elements one position to the right.
- Place the stored element at index 0.
C Program
#include <stdio.h>
int main() {
int arr[100], n, i;
int temp;
printf("Enter number of elements: ");
scanf("%d", &n);
printf("Enter %d elements:\n", n);
for(i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
if(n < 1) {
printf("Rotation not possible.\n");
return 0;
}
// Store last element
temp = arr[n - 1];
// Shift elements to the right
for(i = n - 1; i > 0; i--) {
arr[i] = arr[i - 1];
}
// Place last element at first position
arr[0] = temp;
printf("Array after right rotation by 1 position:\n");
for(i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
Explanation
Step 1: Store Last Element
temp = arr[n - 1];
We save the last element because it will be moved to the first position.
Step 2: Shift Elements
for(i = n - 1; i > 0; i--) {
arr[i] = arr[i - 1];
}
Each element shifts one position to the right.
Step 3: Assign First Position
arr[0] = temp;
Finally, the stored last element becomes the first element.
Sample Input
Enter number of elements: 5 Enter 5 elements: 1 2 3 4 5
Output
Array after right rotation by 1 position: 5 1 2 3 4
Time Complexity
The program uses a single loop to shift elements. Therefore, the time complexity is O(n).
কোন মন্তব্য নেই:
একটি মন্তব্য পোস্ট করুন