222 views
6 6 votes

What is the output of the following code?

#include <stdio.h>

int main() {
    char str[] = {'C', 'S', 'E', '\0', 'X'};

    printf("%s %c", str, str[4]);

    return 0;
}
  1. $\texttt{CSE X}$
     
  2. $\texttt{CSEX X}$
     
  3. $\texttt{CSE \textbackslash0}$
     
  4. $\texttt{Compilation error}$

2 Answers

0 0 votes

 

Here, $\texttt{str}$ is a character array.

The characters are:

$\texttt{str[0] = 'C'}$
$\texttt{str[1] = 'S'}$
$\texttt{str[2] = 'E'}$
$\texttt{str[3] = '\textbackslash0'}$
$\texttt{str[4] = 'X'}$

When a character array is printed using $\texttt{\%s}$, printing continues only until the null character $\texttt{'\textbackslash0'}$.

So, $\texttt{\%s}$ prints only:

$\texttt{CSE}$

The character $\texttt{'X'}$ is present in the array, but it comes after $\texttt{'\textbackslash0'}$, so it is not printed as part of the string.

But $\texttt{str[4]}$ directly accesses the character at index $\texttt{4}$.

So, $\texttt{str[4] = 'X'}$
 

$\therefore$ Output :

$\texttt{CSE X}$
 

Answer: A

• edited by
Answer:
Position:
Show:

Related questions

9 9 votes
2 2 answers
248
248 views
GO Classes asked Jun 24
248 views
What is the output of the following code?#include <stdio.h void change(char *p) { p = 'X'; *(p + 3) = '\0'; } int main() { char str[] = "GATE"; change(str); printf("%s",...
7 7 votes
2 2 answers
219
219 views
GO Classes asked Jun 24
219 views
What is the output of the following code?#include <stdio.h int main() { char str[] = "HELLO"; char *p = str + 1; *(p + 2) = 'A'; printf("%s %c", str, *p); return 0; }$\te...
9 9 votes
2 2 answers
282
282 views
GO Classes asked Jun 24
282 views
What is the output of the following code?#include <stdio.h void fun(int *p) { *p = *p + 1; p++; *p = *p + 2; } int main() { int arr[] = {5, 10, 15}; fun(arr + 1); printf(...
9 9 votes
2 2 answers
277
277 views
GO Classes asked Jun 24
277 views
What is the output of the following code?#include <stdio.h void update(int a[]) { a[0] = a[0] + a ; *(a + 1) = *(a + 1) + 5; } int main() { int arr[] = {2, 4, 6}; update(...