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 7 ■ Functions

7.11 Some Character Functions

In this section, we write several functions relating to characters.

Perhaps the simplest is a function that takes a character as argument; it returns 1 if the

character is a digit and 0, if it is not. (Recall that, in C, a zero value is interpreted as false and a

nonzero value is interpreted as true.) This description suggests that we must write a function that

takes a char argument and returns an int value. We will call it isDigit. Here it is:

int isDigit(char ch) {

return ch >= '0' && ch <= '9';

} //end isDigit

The Boolean expression (ch >= '0' && ch <= '9') is true if ch lies between '0' and '9',

inclusive; that is, if ch contains a digit. Hence, if ch contains a digit, the function returns 1 (for true);

if ch does not contain a digit, it returns 0 (for false).

We could have written the body of the function as

if (ch >= '0' && ch <= '9') return 1;

return 0;

but the single return statement used above is the preferred way.

Similarly, we can write the function isUpperCase, which returns 1 if its argument is an

uppercase letter and 0 if it’s not, thus:

int isUpperCase(char ch) {

return ch >= 'A' && ch <= 'Z';

} //end isUpperCase

Next we have the function isLowerCase, which returns 1 if its argument is a lowercase letter

and 0 if it’s not.

int isLowerCase(char ch) {

return ch >= 'a' && ch <= 'z';

} //end isLowerCase

If we wish to know if the character is a letter (either uppercase or lowercase), we can write

isLetter, which uses isUpperCase and isLowerCase.

int isLetter(char ch) {

int isUpperCase(char), isLowerCase(char);

return isUpperCase(ch) || isLowerCase(ch);

} //end isLetter

Note that we need to include the function prototypes for isUpperCase and isLowerCase.

188

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!