On a 16-bit <em>unsigned int</em>, determine the behavior of this loop (does it terminate, and what does it print)? #include<stdio.h> int main() { unsigned int i = 65535; /* Assume 2 byte integer */ while (i++ != 0) printf("%d", ++i); printf("\n"); return 0; }

Difficulty: Medium

Correct Answer: Infinite loop

Explanation:


Introduction / Context:
This problem explores subtle interactions among post-increment in a loop condition, pre-increment in the body, and modulo arithmetic on a 16-bit unsigned int. Understanding the net change per iteration reveals whether the loop can ever reach the sentinel value 0 in its condition.


Given Data / Assumptions:

  • unsigned int is 16 bits (0..65535).
  • Condition uses i++ (post-increment). Body uses ++i (pre-increment).
  • Arithmetic wraps modulo 65536.


Concept / Approach:
At the first test, i++ yields 65535 (nonzero) and then wraps i to 0. The body runs and ++i sets i to 1 and prints it. Thereafter, each iteration adds 1 in the condition and 1 in the body, for a net increase of 2 per full cycle. Starting from 1 (odd), repeatedly adding 2 cycles through all odd residues modulo 65536. Because 0 is even, the value tested in the next condition (the pre-incremented state from the previous step, then post-incremented) will never be 0 at the moment of comparison. Hence, the loop never terminates.


Step-by-Step Solution:

Initial: i = 65535.Condition: test 65535 → true; i becomes 0.Body: ++i → 1 printed.Next iterations: i advances by +2 overall; it never equals 0 at the instant of comparison.


Verification / Alternative check:
Instrument the code: print i at the top of each loop to observe the odd sequence 1, 3, 5, … wrapping but never hitting 0.


Why Other Options Are Wrong:

Finite sequences require the comparison to become false; it never does.“No output” is impossible because the first iteration certainly prints.


Common Pitfalls:
Overlooking the combined effects of post-increment in the condition and pre-increment in the body; ignoring modulus-wrap properties.


Final Answer:
Infinite loop.

More Questions from Control Instructions

Discussion & Comments

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