`The problem is that you're overwriting your indexes and at end, you come to same values that you've been setting in the beginning. For your case, the programs works like this:
num[4] -> num[0] -- 8 overwrites 55, num = {8,2,37,9,8}
num[3] -> num[1] -- 9 overwrites 2, num = {8,9,37,9,8}
num[2] -> num[2] -- 37 gets set to same index, num = {8,9,37,9,8}
num[1] -> num[3] -- 9 gets set to overwrited value of 2 (now 9), num = {8,9,37,9,8}
num[0] -> num[4] -- 8 gets set to overwrited value of 55 (now 8), num = {8,9,37,9,8}
The most simple solution to understand is (using your code):
int reversedArray[] = new int[num.Length];
for (int i = 1 ; i != 5; i++) {
reversedArray[i - 1] = num[num.length - i];
}
And some tips on your code:
- use
{object type}[] array = ...
instead of {object type} array[]
. Although it works, if you're ever going to transfer to C#, this might give you problems. On the other hand, this is correct syntax for c/c++.
- in
for
loop, instead of initializing i
at 1, start it at 0 as the all arrays are zero-based (this means the first index has a number of 0). This way you can index array only with i
, not having to additionally subtract it.
- Also, for the condition, use
i < array.Length
. This will end 1 number before the number you've put in. For your example, it would loop from 0 to 4 and when it hits 5, it won't repeat the loop again. Again, your syntax works, but the other one is more logical to understand. Also, it might happen (in more complex program scenarios) that looping this way will not give you the result expected, causing you huge headaches because of very simple error.
A more correct solution (applying my tips to your code):
int[] reversedArray = new int[num.Length];
for (int i = 0 ; i < num.Length; i++) {
reversedArray[i] = num[num.length - i];
}
I see that in the time I was writing this, some new questions were added, but I hope that mine helped you understand what was your error and why did it happen.