Skip to content
Official PYQ · 2004

GATE CS 2004 Q33 — Programming in C

Explain with AI

Consider the following C program segment:

char p[20]; int i;
char* s = "string";
int length = strlen(s);
for(i = 0; i < length; i++)
    p[i] = s[length-i];
printf("%s", p);

The output of the program is:

Choose one option
View worked solution

Answer: D

Let's trace the execution of the given C program segment step-by-step:

  1. The string pointer s points to the string literal "string".
  2. The length of the string s is calculated using strlen(s), which is 6 (excluding the null terminator '\0').
  3. The characters of s are indexed from 0 to 6 as follows:
    • s[0] = 's', s[1] = 't', s[2] = 'r', s[3] = 'i', s[4] = 'n', s[5] = 'g'
    • s[6] = '\0' (the null terminator)
  4. The loop runs for i=0i = 0 to i<6i < 6 (i=0,1,2,3,4,5i = 0, 1, 2, 3, 4, 5):
    • For i=0i = 0:
      p[0] = s[6 - 0] = s[6] = '\0'
    • For i=1i = 1:
      p[1] = s[5] = 'g'
    • For i=2i = 2:
      p[2] = s[4] = 'n'
    • For i=3i = 3:
      p[3] = s[3] = 'i'
    • For i=4i = 4:
      p[4] = s[2] = 'r'
    • For i=5i = 5:
      p[5] = s[1] = 't'

After the loop finishes, the array p contains {'\0', 'g', 'n', 'i', 'r', 't', ...}.

When printf("%s", p) is called, it starts printing characters from the beginning of the array p until it encounters the null character ('\0'). Since the very first element p[0] is '\0', the printing terminates immediately, and no output is printed.

Therefore, the correct option is D.

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

Published
Report a correction
Keep exploringMore Programming in C questions