Dad85 - 11 days ago 5
C++ Question

# C++ iteration on first and last elements of array

Let's say I have this array:

``````int oldv[10] = {16, 12, 24, 96, 45, 22, 18, 63, 47, 56};
``````

and another one like

``````int newv[8];
``````

and I want to fill new from alternating ends of
`old`
until a certain condition is met such that I'd have:

``````newv = [16, 56, 12, 47, 24, 63 ...]
``````

Let's say I want to put in new only 3 numbers taken from old (that is: 16, 56, 12).
I've tried with the following for loop, but of course is not enough...

``````for(int i = 0; i < 3; i++)
newv[i] = oldv[i*(sizeof(oldv)-1)];
``````

Any help?

``````int _old[10] = {16, 12, 24, 96, 45, 22, 18, 63, 47, 56};
int _new[8];

const int old_size = sizeof(_old)/sizeof(int);
const int new_size = sizeof(_new)/sizeof(int);

for (int i = 0; i < new_size; ++i)
{
if (i % 2)
_new[i] = _old[old_size - i / 2 - 1];
else
_new[i] = _old[i / 2];

std::cout << _new[i] << " ";
}

std::cout << std::endl;
``````

Returns `16 56 12 47 24 63 96 18`

See it live