ok so i know how mod works but i just cant seem to figure out how this loop after its executes gets there values , ive done it so many times but i just cant seem to figure out how this works can someone plz show me step by step on how this executes

int alpha[5];

int j;

for(j = 0; j < 5; j++)

{

alpha[j] = j + 5;

if(j % 2 == 1)

alpha[j - 1] = alpha[j] + 2;

these are the values the program spits out {8, 6, 10, 8, 9}

int alpha[5];

int j;

for(j = 0; j < 5; j++)

{

alpha[j] = j + 5;

if(j % 2 == 1)

alpha[j - 1] = alpha[j] + 2;

these are the values the program spits out {8, 6, 10, 8, 9}

The output does not correspond to the loop actions. For example alpha[0] can not be equal tp 8 as you showed in the output. It will be equal only to 5.

EDIT:

Oh I am sorry.

Let consider the loop step by step. All elements with even index will be overwritten by value alpha[j] + 2 where j is an odd index.

So at first consider elements of the array with odd indexes. there are two such elements that is with index 1 and with index 3. They will have values 6 ( 1 + 5 ), 8 ( 3 + 5 )

So corresponding elements with even indexes will be equal to

8 ( 6 + 2 ), 10 ( 8 + 2 )

and only the element with index 4 (the last element of the array) will be equal to 9 ( 4 + 5 ).

EDIT:

Oh I am sorry.

Let consider the loop step by step. All elements with even index will be overwritten by value alpha[j] + 2 where j is an odd index.

So at first consider elements of the array with odd indexes. there are two such elements that is with index 1 and with index 3. They will have values 6 ( 1 + 5 ), 8 ( 3 + 5 )

So corresponding elements with even indexes will be equal to

8 ( 6 + 2 ), 10 ( 8 + 2 )

and only the element with index 4 (the last element of the array) will be equal to 9 ( 4 + 5 ).

Last edited on

Topic archived. No new replies allowed.