Sort Elements in Lexicographical Order in C

Exercise:

Write a C Program to sort elements in lexicographical order (dictionary order).

Click Here to View the Solution!
#include <stdio.h>
#include <string.h>
int main() {
    char str[5][50], temp[50];
    printf("Enter 5 words: ");
    for (int i = 0; i < 5; ++i) {
        fgets(str[i], sizeof(str[i]), stdin);
    }
    for (int i = 0; i < 5; ++i) {
        for (int j = i + 1; j < 5; ++j) {
            // swap strings if they are not in the lexicographical order
           if (strcmp(str[i], str[j]) > 0) {
               strcpy(temp, str[i]);
               strcpy(str[i], str[j]);
               strcpy(str[j], temp);
           }
        }
    }
    printf("\nIn the lexicographical order: \n");
    for (int i = 0; i < 5; ++i) {
        fputs(str[i], stdout);
    }
    return 0;
}
Click Here to View the Output!
Enter 5 words: It
is
very
nice
one
In the lexicographical order: 
It
is
nice
one
very
Click Here to View the Explanation!
  • This program is used to arrange the strings in a lexicographical order.
  • In main(), a two dimensional string array str is declared with a size of 5 strings with each string allowed a length of 50 characters.
  • The program requests the user to enter 5 words. The program gets these string inputs and stores them in str using a for loop one at a time.
  • The strings are then stored in a lexicographical order using two nested for loops which iterate through the characters of each string in the 2D string array.
  • The strings are swapped with one another if they are not stored in a lexicographical order by using the strcmp() function.
  • In the if statement, two strings at a time are compared using the strcmp and then if the dictionary order condition is not satisfied, the strings are swapped using the strcpy() function and a temp string array.
  • Finally, all the strings in str are printed in a lexicographical order using a for loop.

%d bloggers like this: