Ashish Rawat
Ashish Rawat

Reputation: 3513

program to find the smallest and largest word

This is an example from K.N. 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.

Upvotes: 1

Views: 7788

Answers (1)

NPE
NPE

Reputation: 500703

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).

Upvotes: 5

Related Questions