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 8 ■ Arrays

Comments on the functionlettersOnlyLower

• i is used to index the given phrase, stored in phrase.

• n is used to index the converted phrase, stored in word.

• The while loop looks at each character of phrase, in turn. If it is a letter, it is

converted to lowercase using the predefined function tolower and stored in

the next position in word; to use tolower, your program must be preceded

by the directive

#include <ctype.h>

• On exit from the while, word is properly terminated with \0.

Putting everything together, we get Program P8.5, which tests our new function,

letterOnlyLower.

Program P8.5

#include <stdio.h>

#include <string.h>

#include <ctype.h>

int main() {

char aPhrase[100], aWord[100];

void lettersOnlyLower(char p[], char w[]);

int palindrome(char str[]);

printf("Type a phrase. (To stop, press 'Enter' only): ");

gets(aPhrase);

while (strcmp(aPhrase, "") != 0) {

lettersOnlyLower(aPhrase, aWord);

printf("Converted to: %s\n", aWord);

if (palindrome(aWord)) printf("is a palindrome\n");

else printf("is not a palindrome\n");

printf("Type a word. (To stop, press 'Enter' only): ");

gets(aPhrase);

} //end while

} //end main

void lettersOnlyLower(char phrase[], char word[]) {

int j = 0, n = 0;

char c;

while ((c = phrase[j++]) != '\0')

if (isalpha(c)) word[n++] = tolower(c);

word[n] = '\0';

224

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!