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.

6.8 Compare Characters

Chapter 6 ■ Characters

Characters can be compared using the relational operators ==, !=, <, <=, > and >=. We’ve

compared the char variable ch with a blank using ch == ' ' and ch != ' '.

Let us now write a program to read a line of data and print the ‘largest’ character, that is, the

character with the highest code. For instance, if the line consisted of English words, the letter that

comes latest in the alphabet would be printed. (Recall, though, that lowercase letters have higher

codes than uppercase letters so that, for instance, 'g' is greater than 'T'.)

‘Finding the largest character’ involves the following steps:

• Choose a variable to hold the largest value; we choose bigChar.

• Initialize bigChar to a very small value. The value chosen should be such

that no matter what character is read, its value would be greater than this

initial value. For characters, we normally use '\0'—the null character, the

‘character’ with a code of 0.

• As each character (ch, say) is read, it is compared with bigChar; if ch is

greater than bigChar, then we have a ‘larger’ character and bigChar is set to

this new character.

• When all the characters have been read and checked, bigChar will contain

the largest one.

These ideas are expressed in Program P6.8.

Program P6.8

//read a line of data and find the 'largest' character

#include <stdio.h>

int main() {

char ch, bigChar = '\0';

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

while ((ch = getchar()) != '\n')

if (ch > bigChar) bigChar = ch; //is this character bigger?

}

printf("\nThe largest character is %c \n", bigChar);

The following is a sample run; u is printed since its code is the highest of all the characters typed.

Type some data and press 'Enter'

Where The Mind Is Without Fear

The largest character is u

155

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!