简体   繁体   中英

program to find the smallest and largest word

This is an example from KN King book which finds the smallest and largest word in a series of words and stops at word length of 4. But it doesn't work correctly.

#include <stdio.h>
#include <string.h>

#define N 20


int main(void) {
    char smallest_word[N];
    char largest_word[N];
    char current_word[N];
    printf("Enter word: ");
    gets(current_word);
    strcpy(smallest_word, strcpy(largest_word, current_word));
    while(strlen(current_word) != 4){
        printf("Enter word: ");
        gets(current_word);
        if(strcmp(current_word, smallest_word) < 0)
            strcpy(smallest_word, current_word);
        if(strcmp(current_word, largest_word) > 0)
            strcpy(largest_word, current_word);

    } 
    printf("\nSmallest word: %s\n", smallest_word);
    printf("Largest word: %s\n", largest_word);
    return 0;
}

Suppose I type:

cat 
dog 
catfish
bear

gives

Output:
Smallest Word: bear
Largest Word: dog

which I think is wrong.

If we arrange the four words in the lexicographic order , we get:

  • bear
  • cat
  • catfish
  • dog

Thus the output looks correct ("bear" is the first, and "dog" is the last).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM