Loop control with a signed char counter: how many values print?\n\n#include<stdio.h>\nint main()\n{\n char j = 1;\n while(j < 5)\n {\n printf("%d, ", j);\n j = j + 1;\n }\n printf("\n");\n return 0;\n}

Difficulty: Easy

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

More Questions from Control Instructions

Discussion & Comments

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