Array logic explanation, please help.

I am trying to get a complete understanding on the topic of arrays. Would anyone help to explain the logic behind this code? I added comments about what I do understand, please correct me if I am wrong.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
 #include <iostream>
using namespace std;

int main()
{

	const int SIZE = 4;

        //variable integer initialized with 4 elements
	int numbers[SIZE] = { 1,2,3,4 };

        //variables temp and i
	int temp, i;

        //integer variable assigned to numbers subscript zero
	int value = numbers[0];

        //for loop starting at subscript 1
        //loop continues from subscript 1 until end of array
        //iterates through each element
	for (i = 1; i < SIZE; i++)
	{
                //Please explain the body of the for loop!

		temp = numbers[i];
		numbers[i] = value;
		value = temp;
	}

        //Please explain this declaration!
	numbers[0] = value;

	for (i = 0; i < SIZE; i++)
		cout << numbers[i] << endl;
	return 0;
}
//integer variable assigned to numbers subscript zero
int value = numbers[0];

value is assigned numbers[0] which is the number 1 from {1,2,3,4} (0,1,2,3 index to get at these)

that for loop swaps the data around.
value is 1 (numbers[0])
loop starts
temp = 2 (numbers[1] is 2)
numbers[1] which was 2 is now 1 (from value)
value = 2 (from temp
final result of first loop is {1,1,3,4}
next loop
... as above, until final result is {1,1,2,3}

numbers[0] = value; //this is not a declaration. this is an assignment.
now the array is {4,1,2,3} as value was 4 and you changed the first location.

what to take away: it is expensive to move data this way in arrays. that is their weakness (every container has a weakness or two which is why we have a dozen container types). Inserting a value in the middle of a sorted array involves manually moving a bunch of items down a space to make room for it, which takes a lot of iteration and time to do. Finally, you don't always have to move the data. Here, for example, *accessing* the array "circularly" soves the problem with no data movement, consider:
for(i = 0; i < size; i++)
cout << array[(i+size-1)%size]; //this loop can replace lines 12-35 and the programs would do the same thing (print 4123)

Last edited on
So does the assignment numbers[0] = value; happen after each individual loop, or at the end of the entire 4 iterations?
Topic archived. No new replies allowed.