Array Rotation Program
Introduction
This program demonstrates how to rotate an array by k positions using C++.
Function Explanation
The rotateArray
function takes an array arr
and an integer k
. It rotates the elements of arr
to the left by k
positions.
arr
: The array to be rotated.k
: Number of positions to rotate the array.
Steps to Rotate the Array
- Create a temporary array
temp
to store the firstk
elements. - Shift the remaining elements of
arr
to the left byk
positions. - Copy elements from
temp
back toarr
to complete the rotation.
Example
Suppose we have an array arr = [1, 2, 3, 4, 5]
and we want to rotate it by k = 2
positions.
After rotation, the array becomes [3, 4, 5, 1, 2]
.
Output
The program outputs the rotated array after performing the rotation.
Rotated array: 3 4 5 1 2
Conclusion
This program efficiently rotates an array in-place by the specified number of positions using C++.
Complete C++ Program
#include <iostream> #include <vector> using namespace std; // Function to rotate array arr[] of size n by d positions void rotateArray(vector<int>& arr, int k) { int n = arr.size(); // To handle cases where k > n k = k % n; // Temporary vector to store elements to be rotated vector<int> temp(arr.begin(), arr.begin() + k); // Shift remaining elements of arr[] to the left for (int i = k; i < n; i++) { arr[i - k] = arr[i]; } // Copy the elements from temp[] to arr[] for (int i = 0; i < k; i++) { arr[n - k + i] = temp[i]; } } int main() { // Example usage vector<int> arr = {1, 2, 3, 4, 5}; int k = 2; // Rotate array by 2 positions // Function call to rotate array rotateArray(arr, k); // Output the rotated array cout << "Rotated array: "; for (int i = 0; i < arr.size(); i++) { cout << arr[i] << " "; } cout << endl; return 0; }