What is the output printed by the following C code? C # include <stdio.h> int…

2008

What is the output printed by the following C code?

C

# 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);
}
 /* Add code here. Remove these lines if not writing code */ 

  1. A.

    dlrow

  2. B.

    Null String

  3. C.

    dlrld

  4. D.

    worow

Attempted by 124 students.

Show answer & explanation

Correct answer: B

Key idea: the for-loop's post-expression a[i++] = a[j--] runs after the (empty) loop body, so the very first assignment copies the null terminator into the first element.

  1. Initial array (indices 0..5): ['w','o','r','l','d','\0']

  2. First loop check: i = 0, j = 5, condition i < j is true. The loop body is empty, then the post-expression runs: a[0] = a[5] which copies '\0' into a[0]; then i becomes 1 and j becomes 4.

  3. Second iteration: i = 1, j = 4. After the (empty) body the post-expression does a[1] = a[4] => 'd'; then i -> 2, j -> 3.

  4. Third iteration: i = 2, j = 3. Post-expression does a[2] = a[3] => 'l'; then i -> 3, j -> 2. Now condition i < j is false, loop ends.

Final array: ['\0','d','l','l','d','\0']

Output: printf prints the string starting at a[0], but a[0] is the null terminator, so nothing is printed before the newline (an empty string followed by a newline).

A video solution is available for this question — log in and enroll to watch it.

Explore the full course: Gate Guidance By Sanchit Sir