in Programming in C
979 views
1 vote
1 vote
int main()
{
    int x=1,y=0,z=1,t;
    for(t=0;t<10;++t)
    {
        y+=x?z:-z;
        z++;
        x=!x;
        printf("y=%d",y);
        }    
}

what will be its output ?
in Programming in C
979 views

1 Answer

2 votes
2 votes

Output will be look like this

y=1
y=-1
y=2
y=-2
y=3
y=-3
y=4
y=-4
y=5
y=-5

Explanation-

Initially the value of y=1,x=0 

for the first time of loop since x=1 , condition ? : is true         // y= y+(x ? z: -z);

so (y+z) i.e,(0+1)=1  will be stored in y ,

now in the line z will be incremented to next value i.e z=2    // z++

and x will be 0   / x= !x

so first time y=1 will be printed .

In the second time of loop

Now the value of x=0 so condition ? : will be false

and hence y - z  i.e ( 1 - 2 ) = -1 will be stored in y.

and similarly z will be incremented to 3 and x will be 1 .

so the second time y=-1 will be printed .

Again in the 3rd time of loop

Now x=1 , so the condition ? : will be true 

and hence y+z i.e (-1+3) = 2 will be stored in y.

and similarly z will be incremented to 4 and x will be 0 .

so the 3rd time y=2 will be printed.

.....and so on 

3 Comments

y = (y+x)?z:-z

why not consider this way
–1
–1
edited by

Sorry Misunderstanding Both are not equal.

Actually  y+=x?z:-z is equal to  y = y + (x±z)  not  y = (y+x) ± z 

eg. a+=b*c+d-e

     a = a +(whole right side expression)

     a = a +(b*c+d-e)    not a = (a + b*c) +(d-e).

0
0
but if it is considered like this,

then in the second loop x=0 and y=1, y+x=0+1=1 therefore will take z and not -z

which ic contrary to the actual evaluation
0
0

Related questions