Skip to content

ISRO Scientist/Engineer CSE 2017Programming in C › Program Output and Loops

ISRO Scientist/Engineer CSE 2017 PYQ: What does the following program do when the input is unsigned 16 bit integer? #include<stdio.h> main(){…

What does the following program do when the input is unsigned 16 bit integer?

#include<stdio.h>
main(){
  unsigned int num;
  int i;
  scanf("%u", &num);
  for(i=0;i<16;i++){
    printf("%d", (num<<i&1<<15)?1:0);
  }
}
  1. A
    It prints all even bits from num
  2. B
    It prints all odd bits from num
  3. C
    It prints binary equivalent of num
    Correct answer
  4. D
    None of above

Answer

(C) It prints binary equivalent of num

Approach

The loop runs i from 0 to 15. In each iteration, the expression (num << i & 1 << 15) shifts num left by i bits and then checks whether the 16th bit (bit 15, the most significant bit) is set. Because shifting left by i moves the original bit at position (15 - i) into position 15, the loop effectively prints the bits of num from most significant to least significant, producing the binary representation of num.

Reviewed by ISRO IQ Editorial Team.