Question

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

ASCII encoding table: A=65, B=66, C=67, ..., Z=90; a=97, b=98, c=99, ..., z=122; *=42, +=43, -=45.
Choose one option
Official answer and solution
Official answer
A
From
Official GATE 2022 answer key

Solution

Compute bitwise AND, OR, and XOR operations on ASCII values and add/subtract character offsets.

Given ASCII values from the table:

  • 'P' = 80 = 01010000201010000_2
  • 'x' = 120 = 01111000201111000_2
  • '*' = 42
  • '-' = 45
  • '+' = 43

Evaluating each variable:

  1. c=(a & b)+’*’c = (a \,\&\, b) + \text{'*'}

    80 & 120=010100002 & 011110002=010100002=8080 \,\&\, 120 = 01010000_2 \,\&\, 01111000_2 = 01010000_2 = 80
    c=80+42=122c = 80 + 42 = 122

    ASCII 122 is 'z'.

  2. d=(a∣b)−’-’d = (a \mid b) - \text{'-'}

    80∣120=010100002∣011110002=011110002=12080 \mid 120 = 01010000_2 \mid 01111000_2 = 01111000_2 = 120
    d=120−45=75d = 120 - 45 = 75

    ASCII 75 is 'K'.

  3. e=(a⊕b)+’+’e = (a \oplus b) + \text{'+'}

    80⊕120=010100002⊕011110002=001010002=4080 \oplus 120 = 01010000_2 \oplus 01111000_2 = 00101000_2 = 40
    e=40+43=83e = 40 + 43 = 83

    ASCII 83 is 'S'.

printf("%c %c %c\n", c, d, e) prints z K S.

Final answer

Option (A)

Common trap

Printing the integer ASCII numbers instead of formatting them as characters using %c.

The answer is the one in the official GATE answer key. The solution is this site's own explanation.

Source

Paper
GATE 2022 Computer Science and Information Technology (CS)
Question
44 of 65
Section
Computer Science and Information Technology

Report an error in this question

GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.