Spot the effect of a stray semicolon after a <code>for</code> loop in C. What does this program print? #include<stdio.h> int main() { int i = 0; for (; i <= 5; i++); printf("%d", i); return 0; }

Difficulty: Easy

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 printf prints the current value of i.


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.Execute printf("%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 the printf 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.

More Questions from Control Instructions

Discussion & Comments

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