Consider the following two C code segments. and are one and two dimensional arrays of size and respectively, where . Assume that in both code segments, elements of are initialized to and each element of array is initialized to . Further assume that when stored in main memory all elements of are in same main memory page frame.
Code segment
// 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
// 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 will be same in both code segments
S2: Elements of array accessed inside the for loop shown in code segment are contiguous in main memory
S3: Elements of array accessed inside the for loop shown in code segment are contiguous in main memory
View worked solution
Answer: C
Let's analyze each statement step-by-step:
1. Analysis of Statement S1
In both code segments, array is initialized to , and each element is initialized to .
- Code Segment 1:
The loop runs for to and performs:
- Code Segment 2:
The loop runs for to and performs:
In both segments, the final contents of array are for all . Therefore, S1 is correct.
2. Analysis of Statement S2
In Code Segment 1, the elements of accessed inside the loop are:
These elements belong to the first row of the 2D array . 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 accessed inside the loop are:
These elements belong to the first column of the 2D array . In row-major storage, elements of the same column across consecutive rows are separated by 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.
