C#.NET — Follow goto-based loop to find printed range. int i = 0, j = 0; label: i++; j += i; if (i < 10) { Console.Write(i + " "); goto label; }
-
APrints 1 to 9
-
BPrints 0 to 8
-
CPrints 2 to 8
-
DPrints 2 to 9
-
ECompile error at label:
Answer
Correct Answer: Prints 1 to 9
Explanation
Introduction / Context:Although goto is rarely recommended in modern C#, this example demonstrates a manual loop using a label and a conditional jump. The question asks you to trace which values of i are printed before the condition fails.
Given Data / Assumptions:
- i and j start at 0; j accumulates but is irrelevant for printing.
- i is incremented before the check and print.
- Printing occurs only when i < 10.
Concept / Approach:Observe the sequence: increment i, update j, test i < 10, print i, and loop via goto. Because i is incremented before the test, the printed sequence begins at 1 and ends at 9, stopping when i becomes 10 (which fails the if condition and the jump does not occur).
Step-by-Step Solution:
Start: i = 0. Increment: i = 1 → i < 10 → print 1 → loop. … continue incrementing and printing: 2, 3, 4, 5, 6, 7, 8, 9. When i increments to 10: the if condition fails; nothing is printed and the loop ends.Verification / Alternative check:Replace goto with a while: i = 0; while (i < 9) { i++; Console.Write(i + " "); } → prints 1..9.
Why Other Options Are Wrong:
- B includes 0, which is never printed.
- C/D shift the range; the code clearly starts at 1 and stops before 10.
- E: labels and goto are legal; no compile error.
Common Pitfalls:Expecting 10 to print; the condition prevents printing when i equals 10.
Final Answer:Prints 1 to 9