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).i++
(post-increment). Body uses ++i
(pre-increment).
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:
++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:
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.
float a = 0.7;
, what will this program print and why?
#includefor
loop in C. What does this program print?
#includeswitch
statement in C? Note the statement before any case
label.
#include
Discussion & Comments