C++ Online Compiler
Example: Circular Array Rotation by One Position Repeatedly in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Circular Array Rotation by One Position Repeatedly #include <iostream> #include <vector> // Using std::vector for dynamic array void rotateArrayOneByOne(std::vector<int>& arr, int k) { int n = arr.size(); if (n == 0) return; // Handle empty array k = k % n; // Normalize k // Perform k rotations for (int rotation_count = 0; rotation_count < k; ++rotation_count) { int last_element = arr[n - 1]; // Store the last element // Shift all elements from n-2 down to 0 one position to the right for (int i = n - 1; i > 0; --i) { arr[i] = arr[i - 1]; } arr[0] = last_element; // Place the stored last element at the beginning } } int main() { // Step 1: Define the array and rotation amount std::vector<int> my_array = {1, 2, 3, 4, 5}; 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 rotateArrayOneByOne(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; // Another example std::vector<int> small_array = {7, 8, 9}; int k_small = 1; std::cout << "\nOriginal Array: "; for (int x : small_array) { std::cout << x << " "; } std::cout << std::endl; rotateArrayOneByOne(small_array, k_small); std::cout << "Rotated Array (k=" << k_small << "): "; for (int x : small_array) { std::cout << x << " "; } std::cout << std::endl; return 0; }
Output
Clear
ADVERTISEMENTS