Question

What is printed by the following ANSI C program?

#include<stdio.h>
int main(int argc, char *argv[])
{
       int a[3][3][3] =
       {{1, 2, 3, 4, 5, 6, 7, 8, 9},
        {10, 11, 12, 13, 14, 15, 16, 17, 18},
        {19, 20, 21, 22, 23, 24, 25, 26, 27}};
        int i = 0, j = 0, k = 0;
        for( i = 0; i < 3; i++ ){
               for(k = 0; k < 3; k++ )
                     printf("%d ", a[i][j][k]);
               printf("\n");
        }
        return 0;
}
Choose one option
Official answer and solution
Official answer
A
From
Official GATE 2022 answer key

Solution

Trace the array indices accessed in the nested loops.

The array a[3][3][3]a[3][3][3] is initialized with 27 elements:

  • Slice i=0i=0: rows of 3 elements: {1,2,3},{4,5,6},{7,8,9}\{1, 2, 3\}, \{4, 5, 6\}, \{7, 8, 9\}
  • Slice i=1i=1: rows of 3 elements: {10,11,12},{13,14,15},{16,17,18}\{10, 11, 12\}, \{13, 14, 15\}, \{16, 17, 18\}
  • Slice i=2i=2: rows of 3 elements: {19,20,21},{22,23,24},{25,26,27}\{19, 20, 21\}, \{22, 23, 24\}, \{25, 26, 27\}

The loop variables are ii (outer loop from 0 to 2) and kk (inner loop from 0 to 2), while jj remains fixed at 00:

  • Outer loop i=0i = 0: prints a[0][0][0],a[0][0][1],a[0][0][2]  ⟹  1 2 3a[0][0][0], a[0][0][1], a[0][0][2] \implies 1\ 2\ 3
  • Outer loop i=1i = 1: prints a[1][0][0],a[1][0][1],a[1][0][2]  ⟹  10 11 12a[1][0][0], a[1][0][1], a[1][0][2] \implies 10\ 11\ 12
  • Outer loop i=2i = 2: prints a[2][0][0],a[2][0][1],a[2][0][2]  ⟹  19 20 21a[2][0][0], a[2][0][1], a[2][0][2] \implies 19\ 20\ 21

Each iteration of the outer loop concludes with a newline, printing:

1 2 3
10 11 12
19 20 21

This matches Option (A).

Final answer

Option (A)

Common trap

Assuming jj increments with ii or kk, whereas jj is constant at 0 throughout.

The answer is the one in the official GATE answer key. The solution is this site's own explanation.

Source

Paper
GATE 2022 Computer Science and Information Technology (CS)
Question
43 of 65
Section
Computer Science and Information Technology

Report an error in this question

GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.