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

The body of the while consists of two statements. These are enclosed by { and } to satisfy C’s

rule that the while body must be a single statement or a block. Here, the body is executed as long

as the character read is not a blank – we write the condition using != (not equal to).

If the character is not a blank, it is printed and the next character read. If that is not a blank,

it is printed and the next character read. If that is not a blank, it is printed and the next character

read. And so on, until a blank character is read, making the while condition false, causing an exit

from the loop.

We would be amiss if we didn’t enlighten you about some of the expressive power in C. For

instance, in Program P6.3, we could have read the character and tested it in the while condition.

We could have rewritten the following three lines:

ch = getchar(); // get the first character

while (ch == ' ') // as long as ch is a blank

ch = getchar(); // get another character

as one line

while ((ch = getchar()) == ' '); // get a character and test it

ch = getchar() is an assignment expression whose value is the character assigned to ch,

that is, the character read. This value is then tested to see if it is a blank. The brackets around ch

= getchar() are required since == has higher precedence than =. Without them, the condition

would be interpreted as ch = (getchar() == ' '). This would assign the value of a condition

(which, in C, is 0 for false or 1 for true) to the variable ch; this is not what we want.

Now that we have moved the statement in the body into the condition, the body is empty; this

is permitted in C. The condition would now be executed repeatedly until it becomes false.

To give another example, in Program 6.4, consider the following code:

char ch = getchar();

while (ch != ' ') {

printf("%c \n", ch)

ch = getchar();

}

// get the first character

// as long as ch is NOT a blank

// print it

// and get another character

This could be re-coded as follows (assuming ch is declared before the loop):

while ((ch = getchar()) != ' ') // get a character

printf("%c \n", ch);

// print it if non-blank; repeat

Now that the body consists of just one statement, the braces are no longer required. Five lines

have been reduced to two!

151

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!