Rule of For in C

0

I have a doubt about the for loop, that is, I have a for statement and I have to get the result that the machine gave. I have this:

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

I know that the variable X starts at 2 and Y at 1. I know that while X is less than 11 it cycles. Here's my problem. Which cycle. I make x + 1 until X has the value of 11? Or I make the rule out that is:

  x=x+1
  y=y+x

Thank you

    
asked by anonymous 21.02.2016 / 20:20

2 answers

3

To understand better, 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 );

Here's 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 at IDEONE .

Briefly, the order of execution is this:

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

After the 5th step, return to the 1st, until the condition of the 2nd give false .

    
21.02.2016 / 20:55
1

All for can be replaced by while .

You may 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 is

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

Where it is well seen that x will be incremented 2 times each time within the cycle.

    
21.02.2016 / 21:17