问题
I am trying to reverse an array of 15 numbers by using a for loop, but for some reason the array order stays the same.
My code looks like this:
int main()
{
int arr[15] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
int i, j, temp;
for (i = 0; i < 15; i++)
{
temp = arr[15 - i - 1];
arr[15 - i - 1] = arr[i];
arr[i] = temp;
}
j = 0;
do {
std::cout << arr[j] << " ";
j++;
} while (j < 15);
}
Any idea what have I done wrong?
回答1:
Yes, you swap all the elements back again once i
is past the half-way point.
To reverse, you only need to go half way; i.e. run i
to 15 / 2.
来源:https://stackoverflow.com/questions/54406620/using-a-for-loop-to-reverse-an-array-does-nothing