Array Rotation Program in C++ Programming Language

 

 

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

  1. Create a temporary array temp to store the first k elements.
  2. Shift the remaining elements of arr to the left by k positions.
  3. Copy elements from temp back to arr 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;
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *