Skip to content
Official PYQ · 2015

GATE CS 2015 Set 3 Q30 — Arrays, Stacks and Queues

Explain with AI

Consider the following two C code segments. YY and XX are one and two dimensional arrays of size nn and n×nn \times n respectively, where 2≤n≤102 \leq n \leq 10. Assume that in both code segments, elements of YY are initialized to 00 and each element X[i][j]X[i][j] of array XX is initialized to i+ji+j. Further assume that when stored in main memory all elements of XX are in same main memory page frame.

Code segment 1:1:

// initialize elements of Y to 0
// initialize elements of X[i][j] of X to i+j
for (i=0; i<n; i++)
    Y[i] += X[0][i];

Code segment 2:2:

// initialize elements of Y to 0
// initialize elements of X[i][j] of X to i+j
for (i=0; i<n; i++)
    Y[i] += X[i][0];

Which of the following statements is/are correct?

S1: Final contents of array YY will be same in both code segments

S2: Elements of array XX accessed inside the for loop shown in code segment 11 are contiguous in main memory

S3: Elements of array XX accessed inside the for loop shown in code segment 22 are contiguous in main memory

Choose one option
View worked solution

Answer: C

Let's analyze each statement step-by-step:

1. Analysis of Statement S1

In both code segments, array YY is initialized to 00, and each element X[i][j]X[i][j] is initialized to i+ji + j.

  • Code Segment 1:

    The loop runs for i=0i = 0 to n−1n-1 and performs:

    Y[i]+=X[0][i]  ⟹  Y[i]=0+(0+i)=iY[i] \mathrel{+}= X[0][i] \implies Y[i] = 0 + (0 + i) = i
  • Code Segment 2:

    The loop runs for i=0i = 0 to n−1n-1 and performs:

    Y[i]+=X[i][0]  ⟹  Y[i]=0+(i+0)=iY[i] \mathrel{+}= X[i][0] \implies Y[i] = 0 + (i + 0) = i

In both segments, the final contents of array YY are Y[i]=iY[i] = i for all 0≤i<n0 \le i < n. Therefore, S1 is correct.

2. Analysis of Statement S2

In Code Segment 1, the elements of XX accessed inside the loop are:

X[0][0], X[0][1], X[0][2], …, X[0][n−1]X[0][0],\, X[0][1],\, X[0][2],\, \dots,\, X[0][n-1]

These elements belong to the first row of the 2D array XX. Since C uses row-major order for storing multi-dimensional arrays, the elements of any single row are stored in contiguous memory locations. Therefore, S2 is correct.

3. Analysis of Statement S3

In Code Segment 2, the elements of XX accessed inside the loop are:

X[0][0], X[1][0], X[2][0], …, X[n−1][0]X[0][0],\, X[1][0],\, X[2][0],\, \dots,\, X[n-1][0]

These elements belong to the first column of the 2D array XX. In row-major storage, elements of the same column across consecutive rows are separated by nn elements (the width of a row). Thus, they are not contiguous in memory. Therefore, S3 is incorrect.

Since only S1 and S2 are correct, the correct option is C.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Arrays, Stacks and Queues questions