retagged by
983 views
9 votes
9 votes

What will be the output of the following C program?

Assume that negative numbers are represented using $2’s$ complement.

#include<stdio.h>
void main()
{
    int a = 2;
    a = ~a+2 << 1;
    printf("%d",a);
}
retagged by

3 Answers

7 votes
7 votes
-2 is Ans.

a = 2 (0000 0010)

precedence order : ~  then + then <<

~a=-3(1111 1101)

~a+2=-3 +2 =-1(1111 1111)

~a+2 « 1 =Left Shift = 1111 1110(Last bit will be 0)

1111 1110 is -2.
edited by
0 votes
0 votes

As , we have given a=2

Now what is ~a ?

it is the Bit-wise NOT operator(~) which gives the complement .

so here ~a =  -(a+1)  

i.e         ~a =   -(3)

now,

 ~a + 2 = -3 + 2 = (-1)

AS ,it is given in question that all the negative numbers are stored in 2’s complement representation

so 2’s complement of  (-1)  is 

(1111 1111)  which is  (255)  in decimal notation.

moving further,

now we have to do left shift on 255. 

[255 « 1]

which is nothing but  255 * 2^1 = 510

so in binary ( 1111 1110)

for the final output we have to again take 2’s complement of 510

which is (0000 0010)  and  (2) in decimal notation.

and as the MSB is 1[in binary notation of 510] thus negative sign must be present.

hence ,

ANS = (-2)

 

0 votes
0 votes

Answer:-2

As we know that ~a+1=-a ,

Rewrite statement a=~a+2<<1; a=~a+1+1  [~a+1=-a]

-a+1<<1;

-2+1<<1

-2

Answer:

Related questions

9 votes
9 votes
1 answer
1