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