-3

Hello could someone explain to me why this code turns out to show this (00 11 21 32 42) on the command prompt when I run the program?

Here's the code:

int main()
{
    int x = 0;
    int y = 0;
    while (x < 5) {
        y = x - y;
        printf("%i%i ", x, y);
        x = x + 1;
    }
    return 0;
}

Thank you.

4

3 回答 3

5

The program loops 5 times, while x is in the range [0,4], printing the values of x and y
The statement y = x - y tells us that y's current value will depend on the current value of x and y's previous value

                   x   y
x = 0  ==>  y = 0 (0 - 0)
x = 1  ==>  y = 1 (1 - 0)
x = 2  ==>  y = 1 (2 - 1)
x = 3  ==>  y = 2 (3 - 1)
x = 4  ==>  y = 2 (4 - 2)
于 2013-03-30T20:57:18.957 回答
2

first iteration:

x=0 y=0-0=0

second:

x=1 y=1-0=1

third:

x=2 y=2-1=1

forth:

x=3 y=3-1=2

fifth:

x=4 y=4-2=2

于 2013-03-30T20:58:55.590 回答
0

In each iteration of the loop, x is incremented by 1 and y (the second digit) is the result of the CURRENT x MINUS the PREVIOUS y.

于 2013-03-30T21:00:49.313 回答