Machine-translated by Google. Questions are authored in English.
Top

Discussion

What will be the output of the program?

#include <stdio.h>

int main()
{
    int n = 12;
    printf("%d %d", n & 1, n >> 1);
    return 0;
}

  • A.0 6
  • B.1 6
  • C.0 24
  • D.12 6

Answer: C

Correct answer: 0 6

Two independent expressions are printed.

n & 1 isolates the least significant bit, which is the parity of the number: it is 1 for odd values and 0 for even ones. Since \( 12 \) is 1100, the low bit is 0, so the first value printed is 0. This is the usual fast alternative to n % 2, and it behaves better on negative numbers, where % in C yields \(-1\) rather than 1.

n >> 1 shifts every bit one place right, discarding the low bit: 1100 becomes 0110, which is 6. That is integer division by two, \( 12 / 2 = 6 \).

So the output is 0 6. Note that the two operations are complementary - the shift keeps everything the mask throws away - which is why they appear together when a number is consumed bit by bit.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.