开发者

C programming while

#include "stdafx.h"
int _tmain(int argc, _TCHAR* argv[])  
{   
    int x=0;
    int y开发者_StackOverflow社区=0;
    while (x<15)y++,x+=++y;
    printf ("%i %i",x, y);
    getchar ();
    getchar ();
    return 0;
}

I don't know why x is 20 and y is 8 at the end. Please explain it step by step.


while (x<15)y++,x+=++y;

=>

while (x<15) {

    y++;
    x += ++y;

}

=>

while (x < 15) {
    y += 2;
    x += y;
}

So:

Before 1st iteration: x = 0, y = 0;

After 1st iteration: x = 2, y = 2;
After 2nd iteration: x = 6, y = 4;
After 3rd iteration: x = 12, y = 6;
After 4th iteration: x = 20, y = 8;

Note that there is a simple closed formula for these values as well: x = n*n - n and y = 2*n.


Remember that :

  1. y++ increments y
  2. x+=++y first increments y and then adds it to x

Which gives the following values for x and y :

iterations   x    y
0            0    0
1            2    2
2            6    4
3            12   6
4            20   8


x<15 -> y=1, x=0+(y=2)=2

2<15 -> y=3, x=2+(y=4)=6

6<15 -> y=5, x=6+(y=6)=12

12<15 -> y=7, x=12+(y=8)=20

Done x=20, y=8

The comma operator enforces the order of execution. x,y means that x is executed first, and then y.


If you follow what is going to happen to your variables :

First Loop:
x=0, y=0
y++ => y=1
x+=++y => x=2, y=2

Second Loop:
x=1, y=2
y++ => y=3
x+=++y => x=6, y=4

Third Loop:
y++ => y=5
x+=++y => x=12, y=6

Fourth Loop:
y++ => y=7
x+=++y => x=20, y=8

And while loop will exit.


I changed it to

#include <stdio.h>
int main()
{
    int x=0;
    int y=0;
    while (x<15) {
        y++,x+=++y;
        printf ("%i %i\n",x, y);
    }
    return 0;
}

and it yields

H:\Temp>a.exe
2 2
6 4
12 6
20 8

now.

Why? Because y gets incremented twice in each step, and x gets added the new value. So you essentially get 2+4+6+8 = 20.

But I'm not sure it is defined behaviour. It is if the , operator defines a sequence point.


Let's go through the loops (conditions after the loop):

  1. x=2, y=2
  2. x=6, y=4
  3. x=12, y=6
  4. x=20, y=8

In each loop, what effectively is done is:

y+=2
x+=y

which results in the states written above.


Alright, this is what is happening every loop in your while clause:

  • Increment y by one
  • Increment y by one additionally
  • add y to x
  • if x >= 15 stop the loop

Now in numbers, right before the end of the loop:

  1. x = 0, y = 0
  2. x = 2, y = 2
  3. x = 6, y = 4
  4. x = 12, y = 6
  5. x = 20, y = 8 --> x > 15 --> finish the loop.


in every iteration

y increased by 2 ( y +=2 ) ,
after that x increased by x + y ( x= x+y)
it skips when x = 20 ( as x is now > 15  ) 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜