Consider the following C program segment. #include int main() { char s1[7] = "1234", *p; p = s1 + 2; *p = '\0'; printf("%s", s1); } What will be printed by the program?
Topic-wise GATE CS PYQs with verified steps
GATE CSE 2015 Set 3 · Q7
Time
#include <stdio.h>
int main()
{
char s1[7] = "1234", *p;
p = s1 + 2;
*p = '\0';
printf("%s", s1);
}What will be printed by the program?Select one answerSingle correct
Solution
Official answer: A) 12
Programming in CLet us trace the execution of the program step by step:
char s1[7] = "1234"; initializes an array of characters where:
s1[0] = '1'
s1[1] = '2'
s1[2] = '3'
s1[3] = '4'
s1[4] = '\0', and remaining elements are zero-initialized.
p = s1 + 2; assigns pointer p to point to s1[2] (the character '3').
*p = '\0'; replaces the character at s1[2] with the null terminator character '\0'.
When printf("%s", s1); is called, it prints the string starting from s1[0] until it encounters the first null character '\0', which is now at index 2.
Therefore, only "12" is printed.
Hence, option (A) is correct.
Try the question first, then check your work.
Examiner trap
In C, string printing with %s terminates as soon as it reaches the first null character ('\0').
This Programming in C previous year question is Q7 of the GATE CSE 2015 Set 3 paper. Find more GATE CSE PYQs on Programming in C in Programming and Data Structures, or browse all GATE CSE PYQs.
Free diagnostic
Take the 20-minute diagnostic: the 3 topics that cost you the most marks, and a rank range. Or sit 5 related Programming in C PYQs now with no account.
An official question by email at 7 AM IST, with a link to its verified solution. Unsubscribe in one click.
Programming in C has 74 GATE CSE PYQs across 25 papers from 2011 to 2026. 20 of them are 1-mark MCQs like this one, and GATE CSE 2015 Set 3 has 4.
How GATE tests Programming in CIndependent practice explanation verified by the GateAI team. GATE is conducted by the IITs; question text follows the official paper.