In C++ (2D array filled by column-major style indexing), what sequence does the program output?
#include
class CuriousTabArray
{
int Matrix[3][3];
public:
CuriousTabArray()
{
for(int i = 0; i < 3; i++)
for(int j = 0; j < 3; j++)
Matrix[j][i] = i + j;
}
void Display(void)
{
for(int i = 0; i < 3; i++)
for(int j = 0; j < 3; j++)
cout << Matrix[j][i] << " ";
}
};
int main()
{
CuriousTabArray objCuriousTab;
objCuriousTab.Display();
return 0;
}
-
AThe program will display the output 4 3 2 3 2 1 2 1 0.
-
BThe program will display the output 0 1 2 1 2 3 2 3 4.
-
CThe program will display the output 9 garbage values.
-
DThe program will report error on compilation.
Answer
Correct Answer: The program will display the output 0 1 2 1 2 3 2 3 4.
Explanation
Introduction / Context: The code writes and then reads a 3x3 matrix using the same Matrix[j][i] indexing order inside nested loops. Although C++ stores arrays in row-major order, the explicit indices determine which element is updated. Because both the constructor and the display use the same indexing, values are read exactly as written.
Given Data / Assumptions:
- Initialization:
Matrix[j][i] = i + jfori, j = 0..2. - Display: prints
Matrix[j][i]in the samei-outer,j-inner order.
Concept / Approach: Compute each entry: For i=0, the row of outputs is 0,1,2; for i=1, outputs are 1,2,3; for i=2, outputs are 2,3,4. Since display mirrors initialization order and indexing, no uninitialized values are printed.
Step-by-Step Solution:
i=0: j=0..2 → 0 1 2 i=1: j=0..2 → 1 2 3 i=2: j=0..2 → 2 3 4 Concatenated: 0 1 2 1 2 3 2 3 4Verification / Alternative check: Swapping indices in Display to Matrix[i][j] would produce a different sequence because the matrix is not symmetric in general for arbitrary formulas.
Why Other Options Are Wrong:
- 4 3 2 ...: Reversed order, not what the loops produce.
- Garbage / Compilation error: All elements are assigned; headers and syntax are fine.
Common Pitfalls: Confusing row-major storage with the iteration order used for printing; storage order does not affect correctness of this deterministic computation.
Final Answer: The program will display the output 0 1 2 1 2 3 2 3 4.