Spot the effect of a stray semicolon after a for loop in C. What does this program print?
#include
int main()
{
int i = 0;
for (; i <= 5; i++);
printf("%d", i);
return 0;
}
-
A0, 1, 2, 3, 4, 5
-
B5
-
C1, 2, 3, 4
-
D6
-
ECompilation error
Answer
Correct Answer: 6
Explanation
Introduction / Context:This exercise highlights a common bug: placing a semicolon immediately after a for loop header. That semicolon makes the loop body empty, and the following statement executes once, after the loop finishes.
Given Data / Assumptions:
- Loop header:
for (; i <= 5; i++);has an empty body. - After the loop, a single
printfprints the current value ofi.
Concept / Approach:The loop increments i from 0 up to 6, stopping when the condition i <= 5 becomes false. The moment the loop terminates, i holds 6. Then, and only then, the printf executes once and prints the final value of i with no newline.
Step-by-Step Solution:
Start: i = 0.Loop runs with empty body while i = 0,1,2,3,4,5.Next increment makes i = 6; condition fails; exit loop.Executeprintf("%d", i); → prints 6.Verification / Alternative check:Add braces to make the intended body explicit or remove the stray semicolon to iterate printing multiple numbers.
Why Other Options Are Wrong:
Sequences like 0..5 would occur only if theprintf were inside the loop body (it is not).5 is not printed; i advances beyond 5 before termination.Compilation error: syntax is legal.Common Pitfalls:Misplacing semicolons after loop headers; forgetting braces for multi-statement bodies.
Final Answer:6.