C Programming

#include "stdafx.h" int _tmain(int argc, _TCHAR* argv[]) { int x=0; int y=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 this step by step.

+4
source share
8 answers
 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 for these values ​​there is also a simple closed formula: x = n*n - n and y = 2*n .

+4
source

Remember, that:

  • y ++ increments y
  • x + = ++ y first increments y and then adds it to x

Which gives the following values ​​for x and y:

 iterations xy 0 0 0 1 2 2 2 6 4 3 12 6 4 20 8 
+3
source

If you follow what happens 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 the cycle is complete.

+1
source

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

Finish x = 20, y = 8

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

+1
source

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 gives

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

Now.

Why? Since y doubles at each step, and x gets a new value. So you essentially get 2 + 4 + 6 + 8 = 20.

But I'm not sure if this is a defined behavior. This is if the operator determines the point of the sequence.

0
source

Go through the loops (conditions after the loop):

  • x = 2, y = 2
  • x = 6, y = 4
  • x = 12, y = 6
  • x = 20, y = 8

In each cycle, the following is effectively performed:

 y+=2 x+=y 

which leads to the above conditions.

0
source

Ok, this is what happens in every loop of your while clause:

  • Y increase by one
  • Increment y with one additional
  • add y to x
  • if x> = 15 stop the cycle

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

  • x = 0, y = 0
  • x = 2, y = 2
  • x = 6, y = 4
  • x = 12, y = 6
  • x = 20, y = 8 β†’ x> 15 β†’ end the cycle.
0
source

at each 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
source

All Articles