#include <stdio.h>
#include <string.h>
int main() {
char words[][50] = {"dog", "cat", "apple", "banana", "zebra", "horse"};
int i, j, n;
char temp[50];
n = sizeof(words)/sizeof(words[0]);
printf("Unsorted words: \n");
for (i = 0; i < n; i++)
printf("%s\n", words[i]);
// Sorting the words in lexicographical order
for (i = 0; i < n-1; i++) {
for (j = i+1; j < n; j++) {
if (strcmp(words[i], words[j]) > 0) {
strcpy(temp, words[i]);
strcpy(words[i], words[j]);
strcpy(words[j], temp);
}
}
}
printf("\nSorted words in lexicographical order: \n");
for (i = 0; i < n; i++)
printf("%s\n", words[i]);
return 0;
}
Unsorted words:
dog
cat
apple
banana
zebra
horse
Sorted words in lexicographical order:
apple
banana
cat
dog
horse
zebra
strcmp ()
function, which returns a negative, zero, or positive value if the first string is lexicographically less than, equal to, or greater than the second string, respectively. strcpy ()
function to swap the two words. Finally, the program prints the unsorted and sorted words.