Loop control with a signed char counter: how many values print? #include<stdio.h> int main() { char j = 1; while(j < 5) { printf("%d, ", j); j = j + 1; } printf(" "); return 0; }
-
A1 2 3 ... 127
-
B1 2 3 ... 255
-
C1 2 3 ... 127 128 0 1 2 3 ... infinite times
-
D1, 2, 3, 4
-
ENo output
Answer
Correct Answer: 1, 2, 3, 4
Explanation
Introduction / Context:This problem examines loop termination with a small integer type. Despite j being a char, the condition is simple and the loop terminates deterministically, illustrating that signedness only matters when overflow or wrap-around could occur.
Given Data / Assumptions:
- j starts at 1.
- The loop increments j until it is no longer less than 5.
- We assume typical 8-bit char, but it does not matter here because values remain small.
Concept / Approach:The body prints j, then increments by 1. The condition is checked again. As soon as j reaches 5, j < 5 becomes false and the loop ends. No overflow occurs because j stays within 1..5.
Step-by-Step Solution:Iteration 1: j=1 → print “1, ” → j=2.Iteration 2: j=2 → print “2, ” → j=3.Iteration 3: j=3 → print “3, ” → j=4.Iteration 4: j=4 → print “4, ” → j=5.Check condition: 5 < 5 → false → exit; newline printed.
Verification / Alternative check:Had the loop been while(j >= 0) with unsigned char, wrap-around could cause an infinite loop. But with a strict upper bound of 5, no wrap-around is reached.
Why Other Options Are Wrong:Long sequences to 127/255 imply missing termination; the program clearly terminates at 4. “Infinite times” is not applicable.
Common Pitfalls:Assuming char arithmetic will wrap in any short loop; forgetting exact loop condition logic; misreading the output formatting (commas and spaces are cosmetic).
Final Answer:1, 2, 3, 4