Ammar Ali - 1 month ago 5x
C++ Question

Why doesn't by program reverse the values of the array correctly?

``````#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!

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;
}
``````