IAE Academy

GATE 2022 CS Q.43: solution and answer

GATE 2022 · CSQ.43 · 2 marks · MCQ

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;
}
  1. (A)

    1 2 3
    10 11 12
    19 20 21

  2. (B)

    1 4 7
    10 13 16
    19 22 25

  3. (C)

    1 2 3
    4 5 6
    7 8 9

  4. (D)

    1 2 3
    13 14 15
    25 26 27

See the question in the paper

Answer and solution

ANSWER

The output is 1 2 3 / 10 11 12 / 19 20 21 — option (A).

Official answer: ASource: Official answer key, GATE 2022 CS (IIT Kharagpur)

  1. Array a[3][3][3] is declared with a flat initializer of 27 values, grouped only two levels deep into three lists of 9: {1..9}, {10..18}, {19..27}.

  2. C fills a multidimensional array in row-major order regardless of how the initializer braces are nested: the rightmost (fastest-varying) index cycles first, so within each outer group of 9, the values fill a[i][0][0..2], then a[i][1][0..2], then a[i][2][0..2].

  3. So a[0][0..2][0..2] = rows (1,2,3),(4,5,6),(7,8,9); a[1][0..2][0..2] = (10,11,12),(13,14,15),(16,17,18); a[2][0..2][0..2] = (19,20,21),(22,23,24),(25,26,27).

  4. j is initialized to 0 and never modified anywhere in the program, so every access uses a[i][0][k].

  5. Outer loop: i runs 0 to 2. Inner loop: k runs 0 to 2, printing a[i][0][k] each time, followed by a newline after the inner loop finishes.

  6. i=0: prints a[0][0][0], a[0][0][1], a[0][0][2] = 1 2 3.

  7. i=1: prints a[1][0][0], a[1][0][1], a[1][0][2] = 10 11 12.

  8. i=2: prints a[2][0][0], a[2][0][1], a[2][0][2] = 19 20 21.

  9. The full output is 1 2 3, 10 11 12, 19 20 21 — this is option (A).

KEY IDEA

A 3-D array a[3][3][3] initialized from a flat, doubly-nested brace list still fills strictly in row-major order (rightmost index varies fastest, regardless of how the initializer braces group the numbers visually). With j fixed at 0, the loops print a[i][0][k] for i = 0..2, k = 0..2, which are the first three elements of each of the three outer i-blocks.

WATCH OUT FOR

Assuming the flat initializer list fills the array in the visually-grouped chunks shown by the braces (giving option C), or confusing which index (i, j, or k) is held fixed and which varies fastest, leading to picking (B) or (D).

From the GATE 2022 CS paper. Every question of this paper · Download the full paper · All 11 Pointers & arrays questions, with notes

More Pointers & arrays questions