cyclically rotate an array by once
#include <iostream>
using namespace std;
void rotateArray(int arr[], int n) {
int temp = arr[n - 1];
for (int i = n - 1; i > 0; i--)
arr[i] = arr[i - 1];
arr[0] = temp;
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Original Array: ";
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
rotateArray(arr, n);
cout << "\nRotated Array: ";
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
return 0;
}
Explanation:
1. rotateArray
function is defined that takes an array arr
and its size n
.
2. temp
stores the last element of the array arr
.
3. A for
loop starts from n - 1
and moves backwards to 1
.
4. Inside the loop, each element is shifted one place to the right.
5. The first element of the array is then assigned the value of temp
(the last element).
6. main
function initializes an array arr
with values {1, 2, 3, 4, 5}
and finds its size.
7. Prints the original array.
8. Calls the rotateArray
function to rotate the array.
9. Prints the rotated array.