I'm not understanding why these values continue to decrease by increments of 2. Because the second loop ends at half of the original array length.
4 Answers
I ran your code just fine. The first loop creates the array and assigns it the values of i * 2. 'i' iterates between 0 and 10, creates the even numbers between 0 and 10*2.
The second loop iterates through half of the values, switching the largest value with the smallest value. It successfully reverses the array. No errors found, good job.
1 Comment
Yes. But I'm not understanding why the values continue to decrease by 2 after 10. Since the second loop stops at half, shouldn't it start going back up from 10 to 12 and so forth till 18? – fer0n 3 hours ago
This would be true if you removed this line:
array [array.length – 1 - i] = array[i];
Comments
The reason why I was not understanding this problem was because I wasn't fully understanding the meaning of arrays. Remember that array[#] is the position within a certain array; the # at that position will not always equal to the value at that position.
The first loop sets the positions from 0 to 9 with values multiplied by 2. Then, the second array is where they swap the values WITHIN these positions.
For example, array[8] does not mean that the int temp equals 8. This simply means that position 8 within the array will be EQUAL to the array[1] from the very first array. Then, we set that original array position equal to the temp value, which is AT position 8.
Now, to understand why it continues to decrease its increment by 2 after 10 since the second loop has ended at position 4, one must look at this line:
array [array.length – 1 - i] = array[i];
For example, when array[9] = array[0], you place the value of 18 from temp into position 0. But you have to look at this line TWICE. The position of array at 9 will equal to the value of 0 because 0 is the value at position of array [0].
array[0]through toarray[9]. Then manually step through the code, writing numbers in these boxes as you do assignments into the array. You might also need another box foriand another box fortemp.