C++ Program for Array Rotation

Last updated on 10/05/2024 0 By indiafreenotes

Array Rotation involves shifting all elements in an array either to the left or to the right by a certain number of positions. In C++, you can implement array rotation efficiently using various approaches such as reversing segments of the array or using a temporary array.

Example program that demonstrates how to rotate an array to the left by a specified number of positions using a temporary array:

#include <iostream>

void rotateArray(int arr[], int size, int positions) {

    // Make sure positions is within the array’s length

    positions = positions % size;

    // Temporary array to hold the elements

    int temp[positions];

    // Copy the first ‘positions’ elements to the temporary array

    for (int i = 0; i < positions; i++) {

        temp[i] = arr[i];

    }

    // Shift the remaining elements to the left

    for (int i = 0; i < size – positions; i++) {

        arr[i] = arr[i + positions];

    }

    // Copy the elements from the temporary array back to the original array

    for (int i = 0; i < positions; i++) {

        arr[size – positions + i] = temp[i];

    }

}

int main() {

    // Define the array

    int arr[] = {1, 2, 3, 4, 5, 6, 7};

    int size = sizeof(arr) / sizeof(arr[0]);

    // Number of positions to rotate the array to the left

    int positions = 2;

    // Rotate the array

    rotateArray(arr, size, positions);

    // Output the rotated array

    std::cout << “Array after rotating left by ” << positions << ” positions: “;

    for (int i = 0; i < size; i++) {

        std::cout << arr[i] << ” “;

    }

    std::cout << std::endl;

    return 0;

}

Here’s how the program works:

  • The function rotateArray takes an array, its size, and the number of positions to rotate as parameters.
  • It uses the modulo operator (%) to ensure the positions parameter is within the bounds of the array’s length.
  • A temporary array is used to hold the first positions elements from the original array.
  • The function shifts the remaining elements in the original array to the left by positions positions.
  • The elements in the temporary array are then copied back to the end of the original array.
  • In the main function, the program prints the array after rotating it to the left by the specified number of positions.