Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

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

Write a C++ program to rotate the elements of a given array of integers (length 4 ) in left direction and return the new array.

Sample Solution:

C++ Code :

#include <iostream>
using namespace std;

int *test(int nums[]) {
   static int  r_array[] = { nums[1], nums[2], nums[3], nums[0] };   
    return r_array;
}

int main () {
   // a pointer to an int.
   int *p;
   int nums[] = {10, 20, 30, 40};	
   
   int arr_length = sizeof(nums) / sizeof(nums[0]);
   cout << "Original array: " << endl;   
   for ( int i = 0; i < arr_length; i++ ) {    
      cout << nums[i] << " ";
   }
   
   p = test(nums);
   cout << "\nRotated array: " << endl;
   for ( int i = 0; i < arr_length; i++ ) {
      cout << *(p + i) << " ";
   }

   return 0;
}

Sample Output:

Original array:
10 20 30 40
Rotated array:
20 30 40 10

Pictorial Presentation:

C++ Basic Algorithm Exercises: Rotate the elements of a given array of integers in left direction and return the new array.

Flowchart:

Flowchart: Rotate the elements of a given array of integers in left direction and return the new array.

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?