Predict the output when using ungetc correctly on stdin. The user repeatedly inputs the character 'a': #include<stdio.h> int main() { int i; char c; for(i=1; i<=5; i++) { scanf("%c", &c); /* given input is 'a' */ printf("%c", c); ungetc(c, stdin); } return 0; } What is printed?

Difficulty: Easy

Correct Answer: aaaaa

Explanation:

Introduction / Context:ungetc allows you to “push back” a character onto an input stream so that a subsequent read returns it again. This pattern can intentionally repeat input.

Given Data / Assumptions:

  • The loop runs five times.
  • Each iteration reads one character from stdin, prints it, then pushes it back onto stdin.
  • The initial input supplied is 'a' and remains available via ungetc for the next iteration.

Concept / Approach:After printing the character, ungetc(c, stdin) ensures that the next scanf("%c", &c) reads the same character again. This repeats for every loop iteration, producing the same output character each time.

Step-by-Step Solution:Iteration 1: read 'a', print 'a', push back 'a'.Iteration 2..5: read the pushed-back 'a', print, push back again.Total visible output: five 'a' characters concatenated.

Verification / Alternative check:Replacing ungetc with no pushback would consume the input and require additional characters to be provided by the user for subsequent iterations.

Why Other Options Are Wrong:aaaa: only four characters; the loop prints five.Garbage value / Error: the code is valid and deterministic here.

Common Pitfalls:Forgetting that ungetc only guarantees one character of pushback; excessive pushback may fail depending on the implementation.

Final Answer:aaaaa

Discussion & Comments

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