The getchar Function

The first time we use getchar is immediately after the first scanf. Here it serves an unusual purpose. Basically it is there solely to soak up the final ENTER which the user pressed after inputting their two numbers. This is a result of a peculiar (and unfortunate) quirk in C.

As you will see, we did not specify in the format string for scanf that the user is expected to input a final ENTER. Indeed we could have included a \n at the end of the format string. However, scanf reads a space, a \n or a \t (standing for TAB) as whitespace. These all tell scanf to skip any whitespace the user might enter at this point. But suggesting scanf skip carriage returns or whitespace at this point merely holds the program up, since although it skips this whitespace, it then waits for more non-whitespace (to be sure that you are done entering whitespace) and another carriage return before it can completely scan the input.

Thus the only way to soak up a final carriage return is by adding a getchar. If we did not do this, there would still be a carriage return waiting in queue to be dealt with by the next function which gets input from the user.