I'm trying to rotate an array to the left, for example rotateLeft3([1, 2, 3]) → [2, 3, 1]
Here is my solution, but it's not working for some reason. Can someone please explain what am I doing wrong ?
#include <iostream>
using namespace std;
int main()
{
bool six;
int Array[3] = { 1,2,3 };
int x = sizeof(Array) / sizeof(Array[0]);
int temp = Array[0];
int temp2;
for (int i = 0; i < x; i++)
{
Array[i] = Array[i + 1];
Array[x - 1] = temp;
}
for (int i = 0; i < 3; i++)
{
cout << Array[i] << endl;
}
system("pause");
return 0;
}
This will be right approach.
So do following changes in your code,
1) Change the Loop Condition to end (x-1)
(otherwise it will be out of bound)
2) Remove the temp assignment inside loop
3) Assign value after the loop ends.
int temp = Array[0];
for (int i = 0; i < x-1; i++){
Array[i] = Array[i + 1];
}
Array[x-1] = temp;
OR
if you want to use inbuilt template then use std::rotate in algorithm header
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With