Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C programming while

Tags:

c

while-loop

#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.

like image 457
Woong-Sup Jung Avatar asked Jan 19 '23 15:01

Woong-Sup Jung


1 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 there is a simple closed formula for these values as well: x = n*n - n and y = 2*n.

like image 59
Paul Avatar answered Jan 21 '23 03:01

Paul