#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 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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With