08.01.2023 Views

Learn to Program with C_ Learn to Program using the Popular C Programming Language ( PDFDrive )

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 6 ■ Characters

A word of caution: we might be tempted to write the following:

printf("The first character is %c \n", getchar());

printf("Its code is %d \n", getchar()); // wrong

But if we did, and assuming that Hello is typed as input, these statements will print:

The first character is H

Its code is 101

Why? In the first printf, getchar returns H, which is printed. In the second printf, getchar

returns the next character, which is e; it is e’s code (101) that is printed.

In Program P6.1, we could use an int variable (n, say) instead of ch and the program would

work in an identical manner. If an int variable is printed using %c, the last (rightmost) 8 bits of the

variable are interpreted as a character and this character is printed. For example, the code for H is

72 which is 01001000 in binary, using 8 bits. Assuming n is a 16-bit int, when H is read, the value

assigned to n will be

00000000 01001000

If n is now printed with %c, the last 8 bits will be interpreted as a character which, of course, is H.

Similarly, if an int value n is assigned to a char variable (ch, say), the last 8 bits of n will be

assigned to ch.

As mentioned, getchar returns the integer value of the character read. What does it return

when the user presses “Enter” or “Return” on the keyboard? It returns the newline character \n,

whose code is 10. This can be seen using Program P6.1. When the program is waiting for you

to type data, if you press the “Enter” or “Return” key only, the first lines of output would be as

follows (note the blank line):

The first character is

Its code is 10

Why the blank line? Since ch contains \n, the statement

printf("\nThe first character is %c \n", ch);

is effectively the same as the following (with %c replaced by the value of ch)

printf("\nThe first character is \n \n");

The \n after is ends the first line and the last \n ends the second line, effectively printing a

blank line. Note, however, that the code for \n is printed correctly.

In Program P6.1, we read just the first character. If we want to read and print the first three

characters, we could do this with Program P6.2.

147

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!