Search⌘ K

Solution Review: Left Rotate Array

Explore how to left rotate an array by one position in C++ using a step-by-step function. Learn to shift array elements accurately and handle edge cases by storing the first element before rotation. This lesson helps you master fundamental array manipulation skills essential for solving array-related challenges.

We'll cover the following...

Solution

Press the RUN button and see the output!

C++
#include <iostream>
using namespace std;
// left_rotate function
void left_rotate(int arr[], int size) {
// Declares a loop counter variable
int j;
// Store the element at index 0
int temp = arr[0];
// Traverse array
for (j = 0; j < size - 1; j++) {
// Left Shift element
arr[j] = arr[j + 1];
}
// Store the value of temp at the last index of an array
arr[j] = temp;
}
// Function to print values of an array
void print_array(int arr[], int size) {
// Traverse array
for (int i = 0; i < size; i++) {
// Print value at index i
cout << arr[i] << " ";
}
cout << endl;
}
// main function
int main() {
// Initialize size of an array
int size = 5;
// Initialize array elements
int arr[size] = {1, 2, 3, 4, 5 };
cout << "Array before left rotation" << endl;
// Call print_array function
print_array(arr, size);
// Call left_rotate function
left_rotate(arr, size);
cout << "Array after left rotation: " << endl;
// Call print_array function
print_array(arr, size);
return 0;
}

Explanation

To left rotate the elements of an array by one index, we move the element of the array at index j+1 to index j, and ...