Consider this C program (preserve the exact newlines):
#include
int main()
{
int x = 10, y = 100%90, i;
for(i = 1; i < 10; i++)
if(x != y);
printf("x = %d y = %d
", x, y);
return 0;
}
Which statements about its output and syntax are correct?
-
A1 only
-
B2 and 3
-
C3 and 4
-
D4 only
-
E1 and 2
Answer
Correct Answer: 2 and 3
Explanation
Introduction / Context:This problem examines how a stray semicolon after an if statement and the absence of braces affect control flow, as well as the behavior of the modulus operator.
Given Data / Assumptions:
- x is 10; y is 100 % 90, which equals 10.
- for loop iterates i from 1 to 9.
- There is a semicolon immediately after if(x != y).
- printf is indented but not braced beneath either if or for.
Concept / Approach:Because of the trailing semicolon, if(x != y); becomes a null statement that executes every loop iteration. The printf line is not part of the if and, due to lack of braces, it is also not part of the for; it executes once after the loop completes. Since x and y are both 10, the printed values are x = 10 y = 10.
Step-by-Step Solution:Compute y: 100 % 90 → 10.Loop: for (i = 1; i < 10; i++) executes a useless if; nothing else in the loop body.After the loop ends, run printf once and print “x = 10 y = 10”.
Verification / Alternative check:Add braces around printf to bind it to for and observe 9 prints; remove the semicolon to bind it to the if and see conditional printing.
Why Other Options Are Wrong:“1 only” claims 10 prints, which is false here. “3 and 4” wrongly asserts no output. “4 only” also says no output, which is incorrect. “1 and 2” includes a false statement.
Common Pitfalls:Relying on indentation rather than braces; missing the effect of a stray semicolon after if; misunderstanding operator % and precedence.
Final Answer:2 and 3