Solution Review: Left Rotate Array
Let's go over the solution review of the challenge given in the previous lesson.
Solution
Press the RUN button and see the output!
Press + to interact
C++
#include <iostream>using namespace std;// left_rotate functionvoid left_rotate(int arr[], int size) {// Declares a loop counter variableint j;// Store the element at index 0int temp = arr[0];// Traverse arrayfor (j = 0; j < size - 1; j++) {// Left Shift elementarr[j] = arr[j + 1];}// Store the value of temp at the last index of an arrayarr[j] = temp;}// Function to print values of an arrayvoid print_array(int arr[], int size) {// Traverse arrayfor (int i = 0; i < size; i++) {// Print value at index icout << arr[i] << " ";}cout << endl;}// main functionint main() {// Initialize size of an arrayint size = 5;// Initialize array elementsint arr[size] = {1, 2, 3, 4, 5 };cout << "Array before left rotation" << endl;// Call print_array functionprint_array(arr, size);// Call left_rotate functionleft_rotate(arr, size);cout << "Array after left rotation: " << endl;// Call print_array functionprint_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 ...