PROGRAM TO SORT STRINGS IN LEXICOGRAPHICAL ORDER
In this example, you will learn a program to sort 5 strings in the lexicographical order i.e. dictionary order.
Output:
Program:
//Program to sort strings in lexicographical order
#include<stdio.h>
#include<string.h>
int main( )
{
char str[5][50], temp[50];
printf("Enter 5 words: ");
// Getting strings input
for (int i = 0; i = 5; ++i)
{
fgets(str[i], sizeof(str[i]), stdin);
}
// storing strings in the lexicographical order
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("\n In the lexicographical order: \n");
for (int i = 0; i = 5; ++i)
{
fputs(str[i], stdout);
}
return 0;
}
#include<stdio.h>
#include<string.h>
int main( )
{
char str[5][50], temp[50];
printf("Enter 5 words: ");
// Getting strings input
for (int i = 0; i = 5; ++i)
{
fgets(str[i], sizeof(str[i]), stdin);
}
// storing strings in the lexicographical order
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("\n In the lexicographical order: \n");
for (int i = 0; i = 5; ++i)
{
fputs(str[i], stdout);
}
return 0;
}
Output:
Enter 5 words: Ruby
Javascript
Java
C programming
C++ programming
In the lexicographical order:
C programming
C++ programming
Java
Javascript
Ruby
Javascript
Java
C programming
C++ programming
In the lexicographical order:
C programming
C++ programming
Java
Javascript
Ruby
So that's it ! Just try this code by your own. If you have any doubts then feel free to drop a comment . I'll be happy to answer your questions .
Keep coding....
Comments
Post a Comment