1,486 views
1 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 ?

1 Answer

2 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 

Position:
Show:

Related questions

1 1 vote
1 1 answer
282
282 views
khanshahima4 asked Sep 24
282 views
1. If precedence tells me which operator has priority, and associativity tells me how to handle operators at the same level, then why do I need a separate concept called ...
14 14 votes
1 1 answer
1.3k
1.3k views
GO Classes asked Jul 2
1,348 views
Assume:$\texttt{short = 2 bytes}$, $\texttt{int = 4 bytes}$, $\texttt{char = 1 byte}$$\texttt{int}$ needs $4$-byte alignment and the final structure size is rounded to a ...
18 18 votes
2 2 answers
752
752 views
GO Classes asked Jul 2
752 views
Assume:struct Student { double gpa; }; struct Student alice; struct Student *sptr = &alice;Which of the following correctly assigns $\texttt{4.0}$ to $\texttt{alice.gpa}$...
10 10 votes
1 1 answer
559
559 views
GO Classes asked Jul 2
559 views
Consider the following code idea from the source:typedef struct { double x, y; } Point; void reset(Point p) { p.x = p.y = 0; } int main() { Point a = {12.0, 42.0}; Point ...