I have an array, where I have to swap the first value with last, second with second last, and so on.
I tried doing it like in the code below, but it only works halfway, replacing the other half with zeros. Could somebody explain what is wrong here, please?
for (i = 0; i < arr.length; i++) {
temp = arr[i];
arr[i] = arr[arr.length - 1 - i];
arr[arr.length - 1 - i] = temp;
}
You have the right idea, but you're iterating over the whole array, so you switch the first and the last elements, and then back again when you reach the last one (and have the same issue for every pair of switched elements). You should stop the loop when you reach half point:
for (i = 0; i < arr.length / 2; i++) { // Here!
temp = arr[i];
arr[i] = arr[arr.length - 1 - i];
arr[arr.length - 1 - i] = temp;
}