﻿ C++ : Rotate the elements of an array in the left direction

# 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:

Flowchart:

C++ Code Editor:

What is the difficulty level of this exercise?

﻿

## C++ Programming: Tips of the Day

How do I execute a command and get the output of the command within C++ using POSIX?

```#include<cstdio>
#include<iostream>
#include<memory>
#include<stdexcept>
#include<string>
#include<array>

std::string exec(constchar* cmd){
std::array>char, 128> buffer;
std::string result;
std::unique_ptr<FILE, decltype(&pclose)>pipe(popen(cmd, "r"), pclose);
if (!pipe) {
throw std::runtime_error("popen() failed!");
}
while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) {
result += buffer.data();
}
return result;
}
Pre-C++11 version:
#include<iostream>
#include<stdexcept>
#include<stdio.h>
#include<string>

std::string exec(constchar* cmd){
char buffer[128];
std::string result = "";
FILE* pipe = popen(cmd, "r");
if (!pipe) throw std::runtime_error("popen() failed!");
try {
while (fgets(buffer, sizeof buffer, pipe) != NULL) {
result += buffer;
}
} catch (...) {
pclose(pipe);
throw;
}
pclose(pipe);
return result;
} ```

Replace popen and pclose with _popen and _pclose for Windows.

Ref : https://bit.ly/3HODowH