C#.NET — Trace an infinite-for loop with conditional decrement and break to predict printed sequence. int i = 20; for (;;) { Console.Write(i + " "); if (i >= -10) i -= 4; else break; }

Difficulty: Easy

Correct Answer: 20 16 12 8 4 0 -4 -8 -12

Explanation:


Introduction / Context:
This program combines an infinite for loop with in-body control using if/else and a break. The test checks whether you correctly follow the order of actions inside the loop: print first, then decide whether to decrement or exit. Many learners get tripped by when the break runs relative to the last printed value.


Given Data / Assumptions:

  • Initial value: i = 20.
  • for (;;) means no header checks; the body controls termination.
  • Console.Write prints i followed by a space on every iteration.
  • If i >= -10, subtract 4; otherwise break.


Concept / Approach:
Remember the exact sequence per iteration: (1) print current i, (2) evaluate i >= -10, (3) either decrement by 4 or break. Because printing occurs before the break check, the terminal value that violates the condition can still be printed on the following iteration's start if it is assigned after the check in the previous round.


Step-by-Step Solution:

Start: i = 20 → print 20 → i >= -10 ⇒ i = 16. i = 16 → print 16 → i = 12. i = 12 → print 12 → i = 8. i = 8 → print 8 → i = 4. i = 4 → print 4 → i = 0. i = 0 → print 0 → i = -4. i = -4 → print -4 → i = -8. i = -8 → print -8 → i = -12. Next iteration: print -12 → now i >= -10 is false → break.


Verification / Alternative check:
Count steps: arithmetic progression descending by 4 until passing -10; the last printed number will be -12 because printing precedes the break test.


Why Other Options Are Wrong:

  • A contains a malformed value (84) and omits the tail.
  • B stops too early and misses negatives.
  • D/E start at 16, but the code prints 20 first.


Common Pitfalls:
Checking the break before printing, or assuming the loop stops at -8. The code prints -12 then exits.


Final Answer:
20 16 12 8 4 0 -4 -8 -12

Discussion & Comments

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