Skip to content
Official PYQ · 2011

GATE CS 2011 Q22 — Programming in C

Explain with AI

What does the following fragment of C program print?

    char c[] = "GATE2011";
    char *p = c;
    printf("%s", p + p[3] - p[1]);
Choose one option
View worked solution

Answer: C

Let's analyze the given C program fragment step-by-step:

  1. Array Initialization:
    char c[] = "GATE2011";
    This creates a character array c containing the string "GATE2011" followed by a null terminator '\0':
    • c[0] = 'G'
    • c[1] = 'A'
    • c[2] = 'T'
    • c[3] = 'E'
    • c[4] = '2'
    • c[5] = '0'
    • c[6] = '1'
    • c[7] = '1'
    • c[8] = '\0'
  2. Pointer Assignment:
    char *p = c;
    The pointer p points to the first element of the array, i.e., &c[0].
  3. Pointer Arithmetic: The expression in the printf statement is:

    Expression=p+p[3]−p[1]\text{Expression} = p + p[3] - p[1]

    Substituting the values of p[3] and p[1]:
    • p[3] is 'E'
    • p[1] is 'A'
    Using their ASCII values (where 'E' = 69 and 'A' = 65):

    p[3]−p[1]=′E′−′A′=69−65=4p[3] - p[1] = 'E' - 'A' = 69 - 65 = 4

    Therefore, the expression simplifies to:

    p+4p + 4

    Since p points to c[0], p + 4 points to c[4].
  4. Printing the String: The %s format specifier prints the string starting from the memory address p + 4 (which is &c[4]) up to the null terminator.

    The characters starting from index 4 are '2', '0', '1', '1', and '\0'.

    Thus, the output is 2011.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Programming in C questions