In C, printf returns the number of characters written. What does this program print (conceptual order of outputs)?
#include
int main()
{
int i;
i = printf("How r u
");
i = printf("%d
", i);
printf("%d
", i);
return 0;
}
Assume a standard ASCII environment.
-
AHow r u 7 2
-
BHow r u 8 2
-
CHow r u 1 1
-
DError: cannot assign printf to variable
-
ENone of the above
Answer
Correct Answer: How r u 8 2
Explanation
Introduction / Context:printf returns an int equal to the number of characters printed (excluding the terminating null). Leveraging this return value is common in code golf and some diagnostic patterns.
Given Data / Assumptions:
- String "How r u" has 8 characters: H o w space r space u and newline.
- "%d" prints the decimal digits of the previous count plus a newline.
- Standard execution with no I/O errors.
Concept / Approach:Track the count returned by each printf and use it in the next call.
Step-by-Step Solution:First printf prints 8 characters → i = 8.Second printf prints "8" → 2 characters → i becomes 2.Third printf prints "2".Reading linearly, the visible outputs are: How r u (newline), then 8, then 2.
Verification / Alternative check:Count characters explicitly: "How r u" = 8. "%d" with i=8 prints 2 characters; the final print shows 2.
Why Other Options Are Wrong:"How r u 7 2": Miscounts the newline."How r u 1 1": Ignores printf's real return values.Error: printf returns int and can be assigned.
Common Pitfalls:Forgetting to count spaces/newlines; assuming printf returns 0 on success (it does not).
Final Answer:How r u 8 2