C++ Exercises: Rotate the elements of a given array of integers in left direction and return the new array
C++ Basic Algorithm: Exercise-85 with Solution
Left Rotate Array (Length 4)
Write a C++ program to rotate the elements of a given array of integers (length 4 ) in the left direction and return the changed array.
Sample Solution:
C++ Code :
#include <iostream> // Including the input/output stream library
using namespace std; // Using the standard namespace
// Function that rotates the elements of an array by one position to the left
int *test(int nums[]) {
// Static array storing the elements after rotation
static int r_array[] = { nums[1], nums[2], nums[3], nums[0] };
return r_array; // Returning the rotated array
}
// Main function
int main () {
int *p; // Pointer to an integer
int nums[] = {10, 20, 30, 40}; // Define an array nums
int arr_length = sizeof(nums) / sizeof(nums[0]); // Calculate the length of nums
cout << "Original array: " << endl;
for ( int i = 0; i < arr_length; i++ ) {
cout << nums[i] << " "; // Output the original array
}
p = test(nums); // Rotate the array and assign it to pointer p
cout << "\nRotated array: " << endl;
for ( int i = 0; i < arr_length; i++ ) {
cout << *(p + i) << " "; // Output the rotated array
}
return 0; // Return statement indicating successful termination of the program
}
Sample Output:
Original array: 10 20 30 40 Rotated array: 20 30 40 10
Visual Presentation:
Flowchart:
C++ Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a C++ program to compute the sum of the elements of a given array of integers.
Next: Write a C++ program to reverse a given array of integers and length 5.
What is the difficulty level of this exercise?
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/cpp-exercises/basic-algorithm/cpp-basic-algorithm-exercise-85.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics