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

The function palindrome is shown in Program P8.4, which tests it by reading several words

and printing whether or not each is a palindrome.

Program P8.4

#include <stdio.h>

#include <string.h>

int main() {

char aWord[100];

int palindrome(char str[]);

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

gets(aWord);

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

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(aWord);

}

} //end main

int palindrome(char word[]) {

int lo = 0;

int hi = strlen(word) - 1;

while (lo < hi)

if (word[lo++] != word[hi--]) return 0;

return 1;

} //end palindrome

In the function, we use the single statement

if (word[lo++] != word[hi--]) return 0;

to express all the logic of the body of the while loop in the above algorithm. Since we use ++ and

-- as suffixes, lo and hi are changed after word[lo] is compared with word[hi].

We could, of course, have expressed it as:

if (word[lo] != word[hi]) return 0;

lo++;

hi--;

The program prompts the user to type a word and tells her if it is a palindrome. It then

prompts for another word. To stop, the user must press the “Enter” or “Return” key only. When

222

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!