For rule in C

Asked

Viewed 105 times

0

I have a doubt about the cycle being , that is, I have an instruction for and I have to get the result that the machine gave. have this :

for(x=2,Y=1;X < 11;x++)y+=x++

I know the X variable starts at 2 and Y at 1. I know as long as X is less than 11, it’s a loop. Here is my problem. Which cycle. do x+1 until X has the value of 11? Or do I make the rule out which is:

  x=x+1
  y=y+x

Thank you

  • I meant instruction . So complicated because I can’t decipher this code. What I want is to know the final result of X and Y

2 answers

3


To better understand, follow your code with some instructions for debug:

int x;
int y;

for( x=2, y=1; x<11; x++ ) {
    printf("antes  x = %d, y= %d \n", x, y );
    y += x++;
    printf("depois x = %d, y= %d \n", x, y );
}
printf("final  x = %d, y= %d \n", x, y );

That is the result:

antes  x = 2, y= 1 
depois x = 3, y= 3 
antes  x = 4, y= 3 
depois x = 5, y= 7 
antes  x = 6, y= 7 
depois x = 7, y= 13 
antes  x = 8, y= 13 
depois x = 9, y= 21 
antes  x = 10, y= 21 
depois x = 11, y= 31 
final  x = 12, y= 31

See working on IDEONE.

Briefly, the order of execution is this:

for( x=2,y=1; X < 11; x++ ) y += x++
     ---1---  ---2--  -5-   --3- -4-

after step 5, return to step 1, until the condition of step 2 false.

  • Thank you very much. I already know what I was missing. I was doing instruction number 4 first and then 3. Thank you

  • 1

    @Chrisadler to do as you said, the line would have to be like this: for( x=2,y=1; X < 11; x++ ) y += ++x . When the ++ comes before the variable, it is processed before the outside expression (is the preincrement). When the ++ comes after, it is only calculated after the expression (post increment). Same thing for the --

1

The whole for can be replaced by a while.

Maybe you find the syntax of while more intuitive :-)

for (initialization; condition; increment) body;
for (initialization; condition; increment) {body};

initialization;
while (condition) {
    body;
    increment;
}

In your specific case, the code stays

// for (x = 2, y = 1; x < 11; x++) y += x++;
x = 2; y = 1;
while (x < 11) {
    y += x++;
    x++;
}

Where you can see very well that x will be incremented 2 times each time within the cycle.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.