IAE Academy

GATE 2022 CS Q.44: solution and answer

GATE 2022 · CSQ.44 · 2 marks · MCQ

What is printed by the following ANSI C program?

#include<stdio.h>

int main(int argc, char *argv[]){
    char a = 'P';
    char b = 'x';
    char c = (a & b) + '*';
    char d = (a | b) - '-';
    char e = (a ^ b) + '+';
    printf("%c %c %c\n", c, d, e);
    return 0;
}

ASCII encoding for relevant characters is given below: A=65, B=66, C=67, ..., Z=90; a=97, b=98, c=99, ..., z=122; *=42, +=43, -=45.

GATE 2022 CS question 44: Three small ASCII reference tables printed below the code: (1) uppercase letters A, B, C,..., Z with codes 65, 66, 67…Tap to open full size
Figure from the GATE 2022 CS paper. It is part of the question.
Figure description

Three small ASCII reference tables printed below the code: (1) uppercase letters A, B, C,..., Z with codes 65, 66, 67,..., 90; (2) lowercase letters a, b, c,..., z with codes 97, 98, 99,..., 122; (3) symbols *, +, - with codes 42, 43, 45.

  1. (A)

    z K S

  2. (B)

    122 75 83

  3. (C)
    • - +
  4. (D)

    P x +

Answer and solution

ANSWER

The program prints z K S, matching option A.

Official answer: ASource: Official answer key, GATE 2022 CS (IIT Kharagpur)

  1. a = P = 80 = 01010000 in binary; b = x = 120 = 01111000 in binary.

  2. c = (a & b) + asterisk: AND gives 01010000 = 80. 80 + 42 = 122 = z.

  3. d = (a | b) - minus: OR gives 01111000 = 120. 120 - 45 = 75 = K.

  4. e = (a ^ b) + plus: XOR gives 00101000 = 40. 40 + 43 = 83 = S.

  5. printf prints c, d, e as characters: output is z K S, matching option A.

KEY IDEA

Bitwise AND/OR/XOR act on the binary ASCII codes of the char operands; the result is combined arithmetically with a symbol's ASCII code, and the resulting integer is printed as a character via percent-c.

WATCH OUT FOR

Mismapping the resulting decimal ASCII code to the wrong letter by miscounting the offset from A, e.g. taking 75 as L instead of K.

From the GATE 2022 CS paper. Every question of this paper · Download the full paper · All 7 C basics questions, with notes

More C basics questions