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

Program P6.2

//read and print the first 3 characters in the data

#include <stdio.h>

int main() {

printf("Type some data and press 'Enter' \n");

for (int h = 1; h <= 3; h++) {

char ch = getchar();

}

}

printf("Character %d is %c \n", h, ch);

The following is a sample run of the program:

Type some data and press 'Enter'

Hi, how are you?

Character 1 is H

Character 2 is i

Character 3 is ,

If we want to read and print the first 20 characters, all we have to do is change 3 to 20 in the for

statement.

Suppose the first part of the data line contains an arbitrary number of blanks, including none.

How do we find and print the first non-blank character? Since we do not know how many blanks

to read, we cannot say something like “read 7 blanks, then the next character.”

More likely, we need to say something like “as long as the character read is a blank, keep

reading.” We have the notion of doing something (reading a character) as long as some ‘condition’

is true; the condition here is whether the character is a blank. This can be expressed more

concisely as follows:

read a character

while the character read is a blank

read the next character

Program P6.3 shows how to read the data and print the first non-blank character. (This code

will be written more concisely later in this section.)

148

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!