Core Concept:
1. Input is stored in a buffer before getchar() reads it.
2. getchar() waits for input only if the input buffer is empty.
Let's understand behaviour of getchar() using this pseudo code :
a = getchar();
b = getchar();
c = getchar();
d = getchar();
e = getchar();
f = getchar();
g = getchar();
Initially our input buffer is empty (as program just started), so at first getchar() program will wait for user for input and suppose user types GATE and presses Enter and so, the buffer becomes : 'G', 'A', 'T', 'E', '\n'
Now, as we know getchar() reads one character at a time from the input buffer, so a = 'G'
Not only that since input buffer still has 4 characters left, so next 4 encounters of getchar() will not wait for user for input instead they will take it from buffer only and which which results in :
a = 'G'
b = 'A'
c = 'T'
d = 'E'
e = '\n'
and At 6th getchar() program again waits for the user to enter input because now buffer is empty as all characters are consumed. Suppose User types 2026 and presses Enter :
So, the buffer becomes : '2', '0', '2', '6', '\n'
Similarly, f = '2' and g = '0' and program ends.
so Remaining buffer : '2', '6', '\n'
These remaining characters stay in the buffer during program execution, but once the program terminates, they are discarded and do not affect any future program executions.
This code demonstrates the behaviour of getchar(), showing that it waits for user input only when the input buffer is empty and otherwise reads characters sequentially from the buffer.
#include <stdio.h>
int main() {
int c;
int buffer_empty = 1; // assume empty at start
for (int i = 1; i <= 7; i++) {
if (buffer_empty) {
printf("ENTER: ");
}
c = getchar();
printf("You entered: '%c'\n", c);
// After '\n' is read, the buffer has been fully consumed.
if (c == '\n') {
buffer_empty = 1;
} else {
buffer_empty = 0;
}
}
return 0;
}
Applying the same concept :
The question states that the input is 1234 followed by a newline, i.e., 1234\n.
So, the input buffer contains: '1', '2', '3', '4', '\n'.
Each call to getchar() reads one character from the buffer.
Thus, the first four calls store '1', '2', '3', and '4' in the variable 'a'.
On the 5th call, getchar() reads '\n', so the recursive calls stop.
As the function returns, putchar() prints the characters in reverse order,
resulting in the output: 4321.