array

hiya, how do I move an array's element up one value, like
array[2] = array[1]
array[3] = array[2]
array[4] = array[3]
etc..
What happens to the first element?
What happens to the last element?

To rotate the elements of the array, do something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>

static constexpr int sz = 6;
int array[sz] = {1, 2, 3, 4, 5, 6};

void print_array() {
  for (int i = 0; i < sz - 1; ++i)
    std::cout << array[i] << ", ";
  std::cout << array[sz - 1] << "\n";
}

int main() {
  print_array();
  
  auto const target_elt = array[sz - 1];
  for (int i = 5; i > 0; --i)
    array[i] = array[i - 1];
  array[0] = target_elt;
  
  print_array();
}


http://coliru.stacked-crooked.com/a/acdea3c375f03cb1
Last edited on
1
2
3
4
5
6
7
8
9
 //consider int arr[10];

 int temp=arr[10-1];
    
 for(int unsigned i=10; i>0;--i)
      arr[i]=arr[i-1];
    
 arr[0]=temp;
    


Array before shifting
1234567890

Array after shifting
0123456789
Last edited on
got it...thanks
memmove function can do this better and faster.
Ive used it to make a side-scroller graphical program, for example, shifting all the pixels over and drawing new only on the edge.



Last edited on
Topic archived. No new replies allowed.