In C (16-bit <em>short int</em>), what will this program print? Assume a short int is 2 bytes. #include<stdio.h> int main() { short int i = 0; for (i <= 5 && i >= -1; ++i; i > 0) printf("%u,", i); return 0; }

Difficulty: Medium

Correct Answer: 1 ... 65535

Explanation:


Introduction / Context:
This problem checks your grasp of the three for clauses in C and how they are evaluated, as well as 16-bit integer overflow behavior. The code uses expressions in unexpected clauses and prints with the %u specifier, which adds to the challenge.


Given Data / Assumptions:

  • short int is 16 bits (range −32768 to 32767).
  • %u prints as unsigned (the argument is int after promotion; although the format is mismatched, typical implementations still display a value).
  • for (init; condition; increment) executes init then condition then body then increment repeatedly.


Concept / Approach:
In this loop, the “init” is the boolean expression i <= 5 && i >= -1 which is evaluated and discarded. The “condition” is ++i, so each iteration starts by incrementing i and testing nonzero. The “increment” is the expression i > 0, which is evaluated and discarded. Thus i climbs from 0 to 1, 2, …; when it passes 32767, it overflows to −32768 and continues up to −1, and the next ++i becomes 0, ending the loop. The printing happens once per iteration.


Step-by-Step Solution:

Start: i = 0.Condition: ++i → 1 (true) → prints 1,.Iterate: i runs across all remaining 16-bit values until ++i yields 0 after wrapping from −1 to 0.Net effect: the program prints values equivalent to 1 through 65535 when viewed as unsigned.


Verification / Alternative check:
Replace %u by %d to see the signed sequence (1, 2, …, 32767, −32768, …, −1). With %u, the negative half renders as 32768…65535, yielding the full 1…65535 run.


Why Other Options Are Wrong:

Expression syntax error: The for clauses are legal expressions.No output or 0..5: contradicted by the loop behavior and wraparound.Infinite loop with no printing: the loop terminates when ++i becomes 0.


Common Pitfalls:
Misinterpreting the role of the three for clauses; expecting the initial clause to assign; overlooking integer overflow wrap in two’s complement.


Final Answer:
1 ... 65535.

More Questions from Control Instructions

Discussion & Comments

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