For starters variable length arrays like this
int n;
cout << "Size of array?\n";
cin >> n;
int x[n];
is not a standard C++ feature. Instead you should use the standard container std::vector<int>
.
To rotate an array or an object of the type std::vector<int>
you can use the standard algorithm std::rotate
.
As for your code then if you want to rotate the array left then this loop
for (int i = 1; i<n; i++) {
swap(x[0],x[i]);
}
should be written like
for (int i = 1; i<n; i++) {
swap(x[i-1],x[i]);
}
Otherwise your loop rotates an array right.
Here is a demonstrative program.
#include <iostream>
#include <utility>
#include <vector>
int main()
{
std::vector<int> v = { 1, 2, 3, 4, 5 };
for ( const auto &item : v )
{
std::cout << item << ' ';
}
std::cout << '\n';
for ( size_t i = 1; i < v.size(); i++ )
{
std::swap( v[i-1], v[i] );
}
for ( const auto &item : v )
{
std::cout << item << ' ';
}
std::cout << '\n';
return 0;
}
The program output is
1 2 3 4 5
2 3 4 5 1
Here is a demonstrative program where there is used the standard algorithm std::rotate
.
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
int main()
{
std::vector<int> v = { 1, 2, 3, 4, 5 };
for ( const auto &item : v )
{
std::cout << item << ' ';
}
std::cout << '\n';
std::rotate( std::begin( v ), std::next( std::begin( v ) ), std::end( v ) );
for ( const auto &item : v )
{
std::cout << item << ' ';
}
std::cout << '\n';
return 0;
}
The program output is the same as shown above
1 2 3 4 5
2 3 4 5 1