C#.NET — Rewrite do-while as an equivalent looping construct. int i = 0; do { Console.WriteLine(i); i += 1; } while (i <= 10);
-
Aint i = 0; do { Console.WriteLine(i); } until (i <= 10);
-
Bint i; for (i = 0; i <= 10; i++) Console.WriteLine(i);
-
Cint i = 0; while (i <= 11) { Console.WriteLine(i); i += 1; }
-
Dint i = 0; do while (i <= 10) { Console.WriteLine(i); i += 1; }
-
Eint i = 0; do until (i <= 10) { Console.WriteLine(i); i += 1; }
Answer
Correct Answer: int i; for (i = 0; i <= 10; i++) Console.WriteLine(i);
Explanation
Introduction / Context:The task is to find an equivalent loop to print integers from 0 through 10 inclusive. We compare do-while, for, and while variants and check boundaries and syntax validity.
Given Data / Assumptions:
- Original code prints 0..10 inclusive with i starting at 0 and incrementing after each print.
- Condition is i <= 10.
Concept / Approach:Translate loop semantics: initialization, condition, increment, and body must match. A for loop with i = 0; i <= 10; i++ matches perfectly.
Step-by-Step Solution:
Initialize i to 0. Ensure termination check i <= 10. Increment i by 1 after each iteration. for (i = 0; i <= 10; i++) Console.WriteLine(i); prints exactly the same sequence.Verification / Alternative check:Count outputs: 11 lines, from 0 to 10 inclusive. The for loop yields identical count and values.
Why Other Options Are Wrong:
- A/E: "until" is not a C# keyword; invalid syntax.
- C: while (i <= 11) prints 0..11; off by one.
- D: "do while" as a single header is invalid syntax in C#.
Common Pitfalls:Off-by-one errors when translating conditions or using the non-existent until syntax in C#.
Final Answer:for (i = 0; i <= 10; i++) Console.WriteLine(i);