C Program to Sort Elements in Lexicographical Order (Dictionary Order)
This program sorts the 5 strings entered by the user in the lexicographical order (dictionary order).
This program takes 5 words (strings) from the user and sorts them in lexicographical order.
Example: Sort strings in the dictionary in order
#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) {
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;
}
Output
Enter 5 words: R programming JavaScript Java C programming C++ programming In the lexicographical order: C programming C++ programming Java JavaScript R programming
To solve this program, two-dimensional string str is created.
This string can hold a maximum of 5 strings and each string can have a maximum of 50 characters (including the null character).
To compare two strings, the strcmp() function is used. And, we used the strcpy() function to copy string to a temporary string, temp.
C program to sort elements in lexicographical order (dictionary order):
#include <stdio.h>
#include <string.h>
int main() {
char str[10][50], temp[50];
int i, j, n;
printf("Enter number of strings:\n");
scanf("%d", &n);
printf("Enter strings:\n");
for (i = 0; i < n; i++)
scanf("%s", str[i]);
for (i = 0; i < n-1; i++) {
for (j = i+1; j < n; j++) {
if (strcmp(str[i], str[j]) > 0) {
strcpy(temp, str[i]);
strcpy(str[i], str[j]);
strcpy(str[j], temp);
}
}
}
printf("Strings in lexicographical order:\n");
for (i = 0; i < n; i++)
printf("%s\n", str[i]);
return 0;
}
Explanation:
#include <stdio.h>
and#include <string.h>
include the standard input-output and string-handling header files respectively in our program.char str[10][50], temp[50];
declares a 2D arraystr
to store the strings and a 1D arraytemp
to store a temporary string during sorting.int i, j, n;
declares three integer variablesi
,j
, andn
.- The
printf()
andscanf()
statements are used to input the number of strings and the strings themselves. - The nested
for
loop starts fromfor (i = 0; i < n-1; i++)
sorts the strings in lexicographical order. Thestrcmp()
function is used to compare the strings and thestrcpy()
function is used to swap the strings if necessary. - The last
for
loop starts fromfor (i = 0; i < n; i++)
prints the sorted strings.
When we compile and run this program, it will prompt the user to input the number of strings and the strings themselves, and then display the sorted strings in lexicographical order.