GATE CS 2015 · Set-3 · Arrays & Matrix Representation

MCQ · 2 marks · Problem PROG-DSTR-0134

Consider the following two C code segments. Y and X are one- and two-dimensional arrays of size n and \(n \times n\) respectively, where \(2 \le n \le 10\). Assume that in both code segments, elements of Y are initialized to 0 and each element X[i][j] of array X is initialized to i+j. Further assume that when stored in main memory all elements of X are in the same main memory page frame.Code segment 1:
// initialize elements of Y to 0
// initialize elements X[i][j] of X to i+j
for (i = 0; i < n; i++)
    Y[i] += X[0][i];
Code segment 2:
// initialize elements of Y to 0
// initialize elements 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 Y will be same in both code segments.S2: Elements of array X accessed inside the for loop shown in code segment 1 are contiguous in main memory.S3: Elements of array X accessed inside the for loop shown in code segment 2 are contiguous in main memory.
  1. A
    Only S2 is correct
  2. B
    Only S3 is correct
  3. C
    Only S1 and S2 are correct
  4. D
    Only S1 and S3 are correct

Solve it on GATE DA practice →More Basic Data Structures problems

Show the worked solutionC stores X in row-major order: X[0][0], X[0][1], ..., X[0][n-1] are adjacent, while X[0][0], X[1][0], X[2][0], ... are n elements apart.S1: segment 1 sets Y[i] = X[0][i] = 0 + i = i; segment 2 sets Y[i] = X[i][0] = i + 0 = i. Same contents: correct.S2: segment 1 reads row 0, X[0][0..n-1]: contiguous, correct.S3: segment 2 reads column 0, whose elements are n (\(\ge 2\)) places apart: not contiguous, incorrect.Answer: C

GATE DA practice: past exam problems by chapter, with worked solutions · gatedaprep.com