997 views
1 votes
1 votes
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 ?

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 

Related questions

0 votes
0 votes
2 answers
1
Debargha Mitra Roy asked Apr 16
122 views
#include <stdio.h int main() { int a[3] = {1, 3, 5, 7, 9, 11}; int *ptr = a[0]; ptr += sizeof(int); printf("%d", *ptr); return 0; }(Assume size of int to be $2$ bytes.)T...
0 votes
0 votes
2 answers
3
Debargha Mitra Roy asked Apr 10
147 views
What is the output of the below code?#include <stdio.h void main() { static int var = 5; printf("%d ", var ); if (var) main(); }a. 1 2 3 4 5b. 1c. 5 4 3 2 1d. Error
1 votes
1 votes
1 answer
4
SSR17 asked Feb 29
277 views
#include <stdio.h int main() { int i = -1; int x = (unsigned char)i; printf("%d", x); return 0; }output is 255 , but please explain how