Using a for loop to reverse an array does nothing [duplicate]

[亡魂溺海] 提交于 2019-12-20 05:45:57

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!