closed by
3,030 views
0 votes
0 votes
closed with the note: Solved
int x=0,i;
    for(i=0;i<10;i++)
    if(i%2 && x++)
     x+=2;

Options:

a: 11

b:13

c:15

d:17
closed by

2 Answers

3 votes
3 votes
int x =0,i;
    for(int i=0;i<10;i++){
        if(i%2 && x++){
            x +=2;
        }
    }

In && operator if first expression is false/0, second expression will not be evaluated.

so, i=0 , i%2=0 , x=0(x remains 0)

i=1 , (i%2=1 && 0) second condition is false, but x will increment. Therefore x =1;

i=2 ,(i%2=0) , x = 1;

i=3,(i%2=1 && 1) , x = 1+1=2 , inside if block x = x+2 = 2+2=4

i =4,(i%2=0) , x = 4;

i=5, (i%2=1 && 4), x=4+1=5 , inside if block x = 5+2 = 7;

i=6, (i%2=0) , x = 7;

i=7, (i%2=1 && 7), x=7+1=8 , inside if block x = 8+2 = 10;

i=8, (i%2=1 && 8), x=10;

i=9, (i%2=1 &&  10), x=10+1=11 , inside if block x = 11+2 = 13;

 

Therefore, Value of x = 13.

 

NOTE : if it was bitwise-AND(&), then even if the first expression is false, second expression will get evaluated.

Therefore for above code with bitwise-AND(&) operator final  value of x=20;

edited by

Related questions

4 votes
4 votes
5 answers
2
ramdas kushwaha asked Feb 19, 2016
6,773 views
Given$(135)_x+(144)_x=(323)_x$What is the value of base $x$ ?
4 votes
4 votes
2 answers
3