C++ Online Compiler
Example: Circular Array Rotation using Temporary Array in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Circular Array Rotation using Temporary Array #include <iostream> #include <vector> // Using std::vector for dynamic array #include <numeric> // For std::iota if needed for initialization (not used in example) void rotateArrayTemp(std::vector<int>& arr, int k) { int n = arr.size(); if (n == 0) return; // Handle empty array k = k % n; // Normalize k to be within array bounds (0 to n-1) // Create a temporary vector to store the last k elements std::vector<int> temp(k); for (int i = 0; i < k; ++i) { temp[i] = arr[n - k + i]; } // Shift the first n-k elements to the right by k positions for (int i = n - 1; i >= k; --i) { arr[i] = arr[i - k]; } // Copy the elements from the temporary vector to the beginning of the original array for (int i = 0; i < k; ++i) { arr[i] = temp[i]; } } int main() { // Step 1: Define the array and rotation amount std::vector<int> my_array = {10, 20, 30, 40, 50}; int k_positions = 2; std::cout << "Original Array: "; for (int x : my_array) { std::cout << x << " "; } std::cout << std::endl; // Step 2: Call the rotation function rotateArrayTemp(my_array, k_positions); // Step 3: Print the rotated array std::cout << "Rotated Array (k=" << k_positions << "): "; for (int x : my_array) { std::cout << x << " "; } std::cout << std::endl; // Example with k > n std::vector<int> another_array = {1, 2, 3}; int k_large = 4; std::cout << "\nOriginal Array: "; for (int x : another_array) { std::cout << x << " "; } std::cout << std::endl; rotateArrayTemp(another_array, k_large); std::cout << "Rotated Array (k=" << k_large << ", normalized to k=1): "; for (int x : another_array) { std::cout << x << " "; } std::cout << std::endl; return 0; }
Output
Clear
ADVERTISEMENTS