Ammar Ali
Ammar Ali

Reputation: 33

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!

Upvotes: 0

Views: 60

Answers (2)

Saurav Sahu
Saurav Sahu

Reputation: 13934

Because you are changing the array in-place, thus changing the initially provided array continuously, and consequently accessing the changed values.

To be able to reverse the array, you mustn't lose the value provided initially till the end of the complete reversing procedure.

Upvotes: 0

Nima Ghotbi
Nima Ghotbi

Reputation: 671

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

Upvotes: 2

Related Questions