The Gateway to Computer Science Excellence

+25 votes

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 \leq n \leq 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 same main memory page frame.

Code segment 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:

// 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 $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

- Only S2 is correct
- Only S3 is correct
- Only S1 and S2 are correct
- Only S1 and S3 are correct

+33 votes

Best answer

Option is **C**. Only $S1$ and $S2$ are correct because $Y$ have same element in both code and in code 1.

Y[i] += X[0][i];

This row major order (In C, arrays are stored in row-major order) which gives address of each element in sequential order$(1,2,3,....,n)$ means we cross single element each time to move next shows contiguous in main memory but in code2 for:

$Y[i] += X[i][0];$

We are crossing n element (row crossing with n element )to move next.

+3

why should we assume that elements are stored in ROW MAJOR ORDER ... why not COLUMN MAJOR ORDER,,, as it is not specified in the question ?

+6

storage of arrays in C is always row major. I found the following reference for this.

http://ee.hawaii.edu/~tep/EE160/Book/chap9/section2.1.2.html

+4

Can anyone explain this statement : "Assume that when stored in main memory, all elements of X are in same main memory page frame"

+6

it fits a page so that when we fetch it , we just have to do one page fetch. contents of single page are stored contiguously in memory. since question is asking about contiguous nature of elements, we need this statement to tell that , by paging , elements are not physically seperated in memory when stored.

+5 votes

answer will be c

as s1 is right(final contents are same ) and s2 as we are getting

consider size of 4

y[0]=0(same as x[0][0])

y[1]=2(as x[0][1]=0+1=1 and y[1]=0+1)

y[2]=1(x[0][2]=0+2=2 and y[2]=0+2)

thus following row major order as in c

as s1 is right(final contents are same ) and s2 as we are getting

consider size of 4

y[0]=0(same as x[0][0])

y[1]=2(as x[0][1]=0+1=1 and y[1]=0+1)

y[2]=1(x[0][2]=0+2=2 and y[2]=0+2)

thus following row major order as in c

52,345 questions

60,519 answers

201,941 comments

95,368 users