Array shifting | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Array shifting

how to keep shifting an array variables to the right as much as you want with c++?

30th Mar 2017, 3:42 AM
Huda Zaher
Huda Zaher - avatar
5 Answers
+ 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; }
30th Mar 2017, 5:09 AM
Hatsy Rei
Hatsy Rei - avatar
+ 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.
30th Mar 2017, 5:01 AM
Hatsy Rei
Hatsy Rei - avatar
+ 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; }
2nd Apr 2017, 4:33 PM
Zeke Williams
Zeke Williams - avatar
+ 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.
30th Mar 2017, 4:04 AM
Zeke Williams
Zeke Williams - avatar
0
recycle it to the beginning.
30th Mar 2017, 4:05 AM
Huda Zaher
Huda Zaher - avatar