How can I move elements in an array to the next element
eg: x[5] = { 5, 4, 3, 2, 1 }; // initial values
x[0] = 6; // new values to be shifted
x[5] = { 6, 5, 4, 3, 2 }; // shifted array, it need to be shifted,
// not just increment the values.
This what I've done so far. It's wrong, that's why I need help here. Thanks in advance.
#include <iostream>
using namespace std;
int main()
{
int x[5] = { 5, 4, 3, 2, 1 };
int array_size = sizeof(x) / sizeof(x[0]);
x[0] = 6;
int m = 1;
for(int j = 0; j < array_size; j++) {
x[m+j] = x[j];
cout << x[j] << endl;
}
return 0;
}
#include<algorithm>
// ...
std::rotate(x, x+4, x+5);
x[0] = 6;
#include <iostream>
int main () {
int x[5] = { 5, 4, 3, 2, 1 };
int array_size = sizeof (x) / sizeof (x[0]);
for (int j = array_size - 1; j > 0; j--) {
x[j] = x[j - 1];
}
x[0] = 6;
for (int j = 0; j < array_size; j++) {
std::cout << x[j];
}
return 0;
}
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