In C, printf returns the number of characters written. What does this program print (conceptual order of outputs)?\n\n#include<stdio.h>\n\nint main()\n{\n int i;\n i = printf("How r u\n");\n i = printf("%d\n", i);\n printf("%d\n", i);\n return 0;\n}\n\nAssume a standard ASCII environment.

Difficulty: Easy

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\n" has 8 characters: H o w space r space u and newline.
  • "%d\n" 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\n" → 2 characters → i becomes 2.Third printf prints "2\n".Reading linearly, the visible outputs are: How r u (newline), then 8, then 2.



Verification / Alternative check:
Count characters explicitly: "How r u\n" = 8. "%d\n" 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

Discussion & Comments

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