coder-coder
coder-coder

Reputation: 353

Simultaneous changes in C++ for-loop

I have the following code:

for (int i = 0; i < 4; i++){
        for (int j = 7; j > 3; j--){
            cout << array[i];
            cout << array[j];
        }
    }

Here, the value of j is changed for four times first, and then the program starts to change the value of i. Edit: Let's say, the array contains numbers that are relevant to their places: array[0] = 0, array[1] = 1 and so on. This method creates the following sequence: 0 7 0 6 0 5 0 4 1 7 ... Instead of this, I would like to have 0 7 1 6 2 5 ... How do I make them change simultaneously?

Upvotes: 1

Views: 146

Answers (3)

Vlad from Moscow
Vlad from Moscow

Reputation: 311048

For example

for ( int i = 0, n = 3, m = 4; i < 4; i++ )
{
    cout << array[n - i];
    cout << array[m + i];
}

Edit: After you changed the code in the question the following way

for (int i = 0; i < 4; i++){
        for (int j = 7; j > 3; j--){
            cout << array[i];
            cout << array[j];
        }
    }

then the loop can look

for ( int i = 0, n = 7; i < 4; i++ )
{
    cout << array[i];
    cout << array[n - i];
}

Upvotes: 1

cigien
cigien

Reputation: 60238

You could use the offset from the end, inside the array, like this:

for(int i = 0; i < 4; ++i)
  cout << array[i] + array[7 - i];

Upvotes: 1

mlc
mlc

Reputation: 415

Another example:

int j = 4;
for (int i = 3; i > -1; i--) {
    cout << array[i];
    cout << array[j];
    j++;
}

Upvotes: 1

Related Questions