0
Array shifting
how to keep shifting an array variables to the right as much as you want with c++?
5 Antworten
+ 15
Ok forget it. It's way back in 2016. This is a redo:
int main()
{
int array[5] = {0,1,2,3,4};
int temp;
bool shift;
while (true)
{
cout << "Input 1 to shift array : "; cin >> shift;
if (shift)
{
temp = array[4];
array[4] = array[3];
array[3] = array[2];
array[2] = array[1];
array[1] = array[0];
array[0] = temp;
}
for (int i = 0; i < 5; i++)
{
cout << array[i] << " ";
}
}
return 0;
}
+ 14
Argh. I've did this as an answer to a question posted here but it's ages ago buried deep in later threads. I'll try to dig around.
+ 3
Or you could have it done a lot more systematically, so it will work with any size of array.
int main() {
int arr[] = {1, 2, 3, 4, 5, 6};
int arrSize = (sizeof(arr)/sizeof(int));
int last = arr[arrSize - 1];
for (unsigned int i = arrSize - 1; i >= 0; i--) {
if (i == 0) {
arr[i] = last;
break;
} else {
arr[i] = arr[i - 1];
}
}
for (unsigned int i = 0; i < arrSize; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
+ 2
What do you want to do with the value that is at the very right end? Do you want to remove it or recycle it to the beginning of the array? After knowing that, it's pretty simple.
0
recycle it to the beginning.