C#.NET — Choose the valid loop that prints all characters of: char[] arr = new char[] { 'k', 'i', 'C', 'i', 't' };

Difficulty: Easy

Correct Answer: foreach (int i in arr) { Console.WriteLine((char) i); }

Explanation:


Introduction / Context:
This question tests valid C# loop syntax and type compatibility when iterating over a character array and printing each element. Several choices intentionally include syntax from other languages or misuse loop headers, so you must pick the one that actually compiles and prints the characters in order.


Given Data / Assumptions:

  • Array: arr = { 'k', 'i', 'C', 'i', 't' }.
  • Goal: print each character on its own line using Console.WriteLine.
  • Allowed constructs: foreach/for/while/do-while in C#.


Concept / Approach:
In C#, foreach (T x in collection) iterates elements of the collection. A foreach variable type must be the element type or a type to which each element can implicitly convert. chars can implicitly convert to int, and casting back to char reproduces the original character for printing. Meanwhile, classic for/while headers must use array.Length, not the array variable itself, and C# does not support an until keyword or variable declarations inside while conditions like shown here.


Step-by-Step Solution:

Option B: foreach (int i in arr) is valid (char → int implicit). Printing (char)i yields each original char. Option C: attempts i < arr which is invalid; must be i < arr.Length. Options A/D/E: misuse declarations/conditions; A and E also use a non-existent until or a do/while form with declarations in the condition.


Verification / Alternative check:
Replace the foreach loop variable with char ch and write Console.WriteLine(ch); It compiles and prints the same sequence.


Why Other Options Are Wrong:

  • A/D/E: syntactically invalid in C#.
  • C: incorrect loop bound (must use arr.Length).


Common Pitfalls:
Forgetting array.Length, or believing foreach must use the exact element type (implicit conversion suffices).


Final Answer:
foreach (int i in arr) { Console.WriteLine((char) i); }

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion