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;
}

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

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

error

Enjoy this blog? Please spread the word :)