edited by
9,629 views
30 votes
30 votes

What is the output printed by the following C code?

# include <stdio.h>
int main ()
{
    char a [6] = "world";
    int i, j;
    for (i = 0, j = 5; i < j; a [i++] = a [j--]);
    printf ("%s\n", a);
}
  1. dlrow
  2. Null string
  3. dlrld
  4. worow
edited by

4 Answers

Best answer
43 votes
43 votes

Char $a[6] = \begin{array}{|l|l|l|l|l|l|} \hline \text{w} &  \text{o} &  \text{r} &  \text{l} &  \text{d} &  \text{\0}\\\hline \end{array}$ 

After the loop executes for the first time, 

$a[0] = a[5]$

$a[0] =$`\0`

Next two more iterations of the loop till $i < j$ condition becomes false, are not important for the output as the first position is '\0';

printf(‘’%s’’, $a$);

printf function for format specifier '%s' prints the characters from the corresponding parameter (which should be an address) until "\0" occurs. Here, first character at $a$ is "\0" and hence it will print NOTHING. 

So, option (B).                  

edited by
23 votes
23 votes

char a[6] = "WORLD"  which be stored like this 

W O R L D \0

Key of this question : there is semicolon (;) after the for loop  , so printf statement will only execute when control will come out of the loop or loop condition will be false.

Iteration 1 : i=0,j=5; 0<5 (condition is true ) ;

                  a[0++] = j[5--] 

/o o r l d \0

 ( here , R.H.S will execute first and j[5--](=null) will be assigned to a[0++] .and then j=5 will be decremented once, bcz post decrement here , same with a[0++] . i will be incremented by one after this statement . )

iteration 2: i=1,j=4 ; 1<4 ( condition is true )

                   a[1++] = j[4--]

\o d r l d \o

iteration 3 :  i=2,j=3; 2<3 (condition is true)

                      a[2++]=j[3--]

\o d l l d \o

iteration 4 : i=3,j=2; 3<2 (condition false )

                    so control will go to the printf statement , and the command inside printf statement is saying print the string present on this address of a  (base address of array) upto null.

but , here first string is null at a[0] . so control will not move further and the output will be null .

so option b is the correct answer.

edited by
2 votes
2 votes

$a[6]=w|o|r|l|d|\setminus0$

$int\ i,j;$

$for(i=0,j=5;i<j;a[i++]=a[j--])$ $;$

$0<5 //condition\ True$

Because of the semi-colon it will not execute the statement instead it will do increment/decrement.

$a[0]=a[5]$

$i=1,j=4$

$1<4 //condition\ True$

$a[1]=a[4]$

$i=2,j=3$

$2<3 //condition\ True$

$a[2]=a[3]$

$i=3,j=2$

$3<2 //condition\ False$

$printf("\%s\setminus n",a)$

Correct Answer (B): Null string

2 votes
2 votes
We can consider like this

for(i=0, j=5 ; i<j ; i++, j--)

{

a[i] = a[j];

}

Therefore a[0] = null char which means end of string. Hence Ans will be Null String.

Thank you for reading.
Answer:

Related questions