Ammar Ali Ammar Ali - 2 months ago 7
C++ Question

Why doesn't my program reverse the values of the array correctly? [Solved]

#include <iostream>
using namespace std;
int main ()
{
int myArray [5] = {10, 20, 30, 40, 50};
for(int count = 0; count < 5; count++)
{
myArray[count] = myArray[4-count];
}

for(int Count = 0; Count < 5; Count++)
{
cout<<myArray[Count]<<endl;
}
}


Output is 50,40,30,40,50 instead of 50,40,30,20,10. Any idea what's wrong with the logic of this program? Thanks for your time!

Answer

Let's go over the code one iteration at a time:

 myArray [5] = {10, 20, 30, 40, 50};

1st iteration:

 myArray [5] = {50, 20, 30, 40, 50};

2nd iteration:

 myArray [5] = {50, 40, 30, 40, 50};

3rd iteration:

 myArray [5] = {50, 40, 30, 40, 50};

4th iteration:

 myArray [5] = {50, 40, 30, 40, 50};

5th iteration:

 myArray [5] = {50, 40, 30, 40, 50};

to make it work as expected change the loop to swap the values insist of overwriting them. like:

for (i = 0; i < 2; ++i) {
    tmp = arr[4-i];
    myArray[4-i] = myArray[i];
    myArray[i] = tmp;
}
Comments