C#.NET — Complete the foreach so that all elements of the jagged array are printed: int[][] a = new int[2][]; a[0] = new int[4] { 6, 1, 4, 3 }; a[1] = new int[3] { 9, 2, 7 }; foreach (int[] i in a) { /* Add loop here */ Console.Write(j + " "); Console.WriteLine(); }
Correct Answer: foreach (int j in i)
Introduction / Context:Jagged arrays are arrays of arrays. To iterate every value, first enumerate each inner array, then enumerate its elements.
Given Data / Assumptions:
aisint[][]with rows of different lengths.- The outer foreach provides each inner array as
i.
Concept / Approach:The idiomatic nested foreach is: foreach (int[] i in a) { foreach (int j in i) { ... } }. This naturally handles different row lengths without index math.
Step-by-Step Solution:
Outer loop: iterates inner arrays (i is an int[]).Inner loop: iterate values in i → foreach (int j in i).Print each j followed by a space, then write a newline per row.Verification / Alternative check:Run the code; it prints 6 1 4 3 on the first line and 9 2 7 on the second, matching the jagged structure.
Why Other Options Are Wrong:
- A/B: Use for-loop syntax or invalid calls; also not appropriate for jagged enumeration.
- C/E:
a.Lengthis a scalar; you cannot foreach over anint.
Common Pitfalls:Confusing rectangular array APIs (like GetUpperBound) with jagged arrays, which are just arrays whose elements are arrays.
Final Answer:foreach (int j in i)