Question:
How do you shift elements in a array?
Biig D
2011-02-19 15:38:19 UTC
I recently missed a week in school due to an unprecedented illness and am currently trying to finish a good amount of make up work in my classes. However on one of my assignments in my Ap comp. class I have no idea what to do. It involves moving elements in a array around and switching their order (to the left, or right) and copying elements in a array as well. I have 2 examples of what I'm talking about here:

Write a program that will shift the values of an array one position to the left. For example, suppose we have an array of integers called Matrix that stores the sequence of values (15, 4, 8, 9, 7, 11, 12) and we want to rotate the values so that the value at the front of the list goes to the back and the order of the other values stays the same. In other words, we want to move the 15 to the back, yielding the list (4, 8, 9, 7, 11, 12, 15).

Before shifting int [] Matrix={15, 4, 8, 9, 7, 11, 12};

After shifting int [] Matrix={4, 8, 9, 7, 11, 12, 15};

And

Write a program that will first create Array1 and initialized with the following elements
(20, 30, 40, 50, 60), Array2 with the following elements (11, 12, 13, 14, 15). The program will copy the elements of Array1 into Array2 and print the final values of Array2.

Before: int [] Array1={20, 30, 40, 50, 60};
int [] Array 2={11, 12, 13, 14, 15};

After: int [] Array1={20, 30, 40, 50, 60};
int [] Array2={20, 30, 40, 50, 60};

Can anyone give me a detailed explanation on how this is to be done?
Three answers:
The Phlebob
2011-02-19 19:33:45 UTC
The key thing here is that each element in an array can be used or stored into independent of any other element. So for example, you could do this:



Matrix[0] = Matrix[2];



or



Array1[ 2 ] = Array2[ 2 ];



And all the other elements in both arrays would remain unaffected.



Now for your first program, you have to analyze what has to happen to the array values to make the transformation, then write the code that does it. For the second, you have to copy Array1[] into Array2[]. A big hint: When dealing with array element manipulation, you almost always deal with a loop, usually a for-loop. This is true in both the programs you need to write.



Hope that helps.
tbshmkr
2011-02-19 16:47:38 UTC
Try This

=

How to shift array elements

- http://stackoverflow.com/questions/765863/how-to-shift-array-elements

C++ program to shift elements in an array?

- https://answersrip.com/question/index?qid=20100406010246AAI346R
2011-02-20 01:31:15 UTC
for(int i = 0; i < n; i++)

array_dest[i] = array_source[(i+1)%n];


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...